UNPKG

immutable-js

Version:
131 lines (115 loc) 3.45 kB
/** * 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 { KeyedCollection } from './Collection'; import { IS_MAP_FLAG, isMap } from './Flags'; import { nullOrUndefined } from './util/is'; import { typedef as defineTypeOf } from './util/toolset'; import { NativeObject, isNative } from './Native'; export var MAP_TYPEDEF = '[KeyedCollection Map]'; export class Map extends KeyedCollection { constructor(value) { return value ? makeMap(value) : emptyMap(); } has(key) { if(key && !nullOrUndefined(this.__internal[key])) { if(this.__internal.hasOwnProperty(key)) { return true; } } return false; } get(key, notSetValue) { if(key && this.has(key)) { return this.__internal[key]; } return notSetValue; } set(key, value) { if(this.__ownerID) { this.__internal[key] = value; this.__altered = true; return this; } var updated = this.__internal.__clone(); updated[key] = value; return makeMap(updated, null); } remove(key) { if(!key || !this.has(key)) { return this; } if(this.__ownerID) { delete this.__internal[key]; this.size = this.size--; this.__altered = true; return this; } var copied = this.__internal.__clone(); delete copied[key]; return makeMap(copied); } clear() { if(this.size === 0) { return this; } if(this.__ownerID) { this.size = 0; this.__altered = true; this.__internal = new NativeObject(); return this; } return makeMap(new NativeObject(null)); } __iterate(handle, reverse) { var object = this.__internal; var keys = this.__keys || Object.keys(object); var maxIndex = keys.length - 1; for(var n = 0; n <= maxIndex; n++) { let key = keys[reverse ? maxIndex - n: n]; if(handle(object[key], key, this) === false) { return n + 1; } } return n; } wasAltered() { return this.__altered; } toString() { return this.__toString('Map {', Object.keys(this.__internal).map((v, index) => { return typeof this.__internal[v] === 'string' ? JSON.stringify(this.__internal[v]) : this.__internal[v]; }),'}'); } toMap() { return this; } } var EMPTY_MAP; export function emptyMap() { return EMPTY_MAP || (EMPTY_MAP = makeMap()); } export function makeMap(init, ownerID) { var map = Object.create(Map.prototype); map.__internal = new NativeObject(); map.__ownerID = ownerID; map.__altered = false; if(init && (isNative(init) || (typeof init === 'object'))) { map.__internal = map.__internal.extend(init); } map.size = Object.keys(map.__internal).length; return map; } defineTypeOf({ Map: MAP_TYPEDEF }); Map.prototype[IS_MAP_FLAG] = true; Map.isMap = isMap;