Skip to content
Snippets Groups Projects
lib.js 994 B
Newer Older
clemo's avatar
clemo committed
import debug from 'debug';
import Math from './math.js';
const log = debug('helper:lib');
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) {
    log("add item", item);
    if ("function" === typeof this._hooks['beforeAdd']) {
      item = this._hooks['beforeAdd'](item);
    }
    if (item.id) {
      // todo: check unique
    } else {
      item.id = new Math().uuid();
    }
    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;