immutable-js
Version:
Immutable types in JavaScript
120 lines (105 loc) • 3.2 kB
JavaScript
/**
* Copyright (c) 2015, Jan Biasi.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { IndexedCollection } from './Collection';
import { IS_LIST_FLAG, isList } from './Flags';
import { NativeArray, NativeObject, isNative } from './Native';
import { nullOrUndefined } from './util/is';
import { typedef as defineTypeOf } from './util/toolset';
export var LIST_TYPEDEF = '[IndexedCollection List]';
export class List extends IndexedCollection {
constructor(value) {
return arguments.length > 1 ? makeList(
Array.prototype.slice.call(arguments)
) : makeList(value);
}
static of (...values) {
return this(values);
}
toString() {
return this.__toString('List [', this.__internal.join(',') ,']');
}
push(...values) {
if(this.__ownerID) {
values.forEach(v => this.__internal.push(v));
this.size = this.__internal.length;
this.__altered = true;
return this;
}
return makeList(this.__internal.__clone().concat(values));
}
shift() {
if(this.__ownerID) {
this.__internal.pop();
this.size = this.__internal.length;
this.__altered = true;
return this;
}
var cloned = this.__internal.__clone();
var newSize = cloned.pop();
return new List(cloned);
}
clean() {
if(this.size === 0) {
return this;
}
if(this.__ownerID) {
this.__altered = true;
this.__internal = new NativeArray();
this.size = this.__internal.length;
return this;
}
return emptyList();
}
__iterator(handle, reverse) {
}
__ensureOwner(ownerID) {
if(ownerID === this.__ownerID) {
return this;
}
if(!ownerID || nullOrUndefined(ownerID)) {
this.__ownerID = ownerID;
this.__altered = false;
return this;
}
return makeList(this.__internal, ownerID);
}
}
var EMPTY_LIST;
function emptyList() {
return EMPTY_LIST || (EMPTY_LIST = makeList(null));
}
function makeList(values, ownerID) {
var list = Object.create(List.prototype);
list.__ownerID = ownerID;
list.__altered = false;
list.__internal = new NativeArray();
list.size = 0;
if(nullOrUndefined(values)) {
return list;
} else if(isNative(values)) {
list.__internal = values;
} else if (Array.isArray(values)) {
list.__internal = new NativeArray();
values.forEach((value, index) => {
list.__internal.push(value);
});
list.size = list.__internal.length;
} else {
throw TypeError(
'Expected an array or values as input and not ' +
typeof values
);
}
return list;
}
defineTypeOf({
List: LIST_TYPEDEF
});
List.prototype[IS_LIST_FLAG] = true;
List.isList = isList;