70 lines
1.7 KiB
JavaScript
70 lines
1.7 KiB
JavaScript
'use strict';
|
|
exports.Map = LazyMap; // TODO: use ES6 map
|
|
exports.Set = LazySet; // TODO: use ES6 set
|
|
// based on https://github.com/montagejs/collections
|
|
function LazyMap() {
|
|
this.store = {};
|
|
}
|
|
LazyMap.prototype.mangle = function (key) {
|
|
if (typeof key !== "string") {
|
|
throw new TypeError("key must be a string but Got " + key);
|
|
}
|
|
return '$' + key;
|
|
};
|
|
LazyMap.prototype.unmangle = function (key) {
|
|
return key.substring(1);
|
|
};
|
|
LazyMap.prototype.get = function (key) {
|
|
var mangled = this.mangle(key);
|
|
if (mangled in this.store) {
|
|
return this.store[mangled];
|
|
}
|
|
return void 0;
|
|
};
|
|
LazyMap.prototype.set = function (key, value) {
|
|
var mangled = this.mangle(key);
|
|
this.store[mangled] = value;
|
|
return true;
|
|
};
|
|
LazyMap.prototype.has = function (key) {
|
|
var mangled = this.mangle(key);
|
|
return mangled in this.store;
|
|
};
|
|
LazyMap.prototype.delete = function (key) {
|
|
var mangled = this.mangle(key);
|
|
if (mangled in this.store) {
|
|
delete this.store[mangled];
|
|
return true;
|
|
}
|
|
return false;
|
|
};
|
|
LazyMap.prototype.forEach = function (cb) {
|
|
var keys = Object.keys(this.store);
|
|
for (var i = 0, len = keys.length; i < len; i++) {
|
|
var key = keys[i];
|
|
var value = this.store[key];
|
|
key = this.unmangle(key);
|
|
cb(value, key);
|
|
}
|
|
};
|
|
|
|
function LazySet(array) {
|
|
this.store = new LazyMap();
|
|
|
|
// init with an array
|
|
if (array && Array.isArray(array)) {
|
|
for (var i = 0, len = array.length; i < len; i++) {
|
|
this.add(array[i]);
|
|
}
|
|
}
|
|
}
|
|
LazySet.prototype.add = function (key) {
|
|
return this.store.set(key, true);
|
|
};
|
|
LazySet.prototype.has = function (key) {
|
|
return this.store.has(key);
|
|
};
|
|
LazySet.prototype.delete = function (key) {
|
|
return this.store.delete(key);
|
|
};
|