UNPKG

collectionsts

Version:

collectionsts =============

66 lines (65 loc) 1.78 kB
function generateHash() { return Math.random().toString(36).slice(2); } var Collection = (function () { function Collection() { this._items = { }; this._length = 0; } Object.defineProperty(Collection.prototype, "length", { get: function () { return this._length; }, enumerable: true, configurable: true }); Collection.prototype.get = function (id) { if(!this._items[id]) { return null; } else { return this._items[id]; } }; Collection.prototype.getHash = function () { var hash = generateHash(); while(this._items[hash] !== undefined) { hash = generateHash(); } return hash; }; Collection.prototype.add = function (elem) { if(!elem.uid) { elem.uid = this.getHash(); } this._items[elem.uid] = elem; this._length++; }; Collection.prototype.remove = function (elem) { this.removeById(elem.uid); }; Collection.prototype.removeById = function (id) { this._items[id] = undefined; this._length--; }; Collection.prototype.forEach = function (op) { var i = 0; for(var id in this._items) { op(this._items[id], id, i++, this); } }; Collection.prototype.toArray = function () { var arr = new Array(this.length); this.forEach(function (elem, id, i) { arr[i] = elem; }); return arr; }; return Collection; })(); exports.Collection = Collection; function toUnique(obj, id) { obj.uid = id; return obj; } exports.toUnique = toUnique;