import debug from 'debug'; import Math from './math.js'; const log = debug('helper:lib:info'); const error = debug('helper:lib:error'); export class Lib { constructor() { this.items = []; this._hooks = {}; } getById(id) { return this.getArray().filter((item) => (item.id === id))[0]; } getArray() { return this.items.filter((item) => (!item._remove)); } add(item, overwrite = false) { log("add item", item); if ("function" === typeof this._hooks['beforeAdd']) { item = this._hooks['beforeAdd'](item); } if ('undefined' === typeof item.id) { item.id = new Math().uuid(); } let existingItem = this.getById(item.id); if ("undefined" !== typeof existingItem) { if (overwrite) { existingItem = item; return existingItem; } else { return log('add duplicate', 'item with this id already exist overwrite != true'); } } else { this.items.push(item); return item; } } setHook(type, fn) { log('setHook', type, fn); this._hooks[type] = fn; } remove(id) { log('remove item', id); this.getById(id)._remove = true; } each(cb) { let items = this.getArray(); for (let i = items.length; i >= 0; i--) { if (items[i] && items[i].id !== null) { cb(items[i]); } } } } export default Lib;