all files / lib/ lib.js

100% Statements 35/35
100% Branches 16/16
100% Functions 9/9
100% Lines 33/33
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55   124762× 125772× 507× 507× 507×   507×   507× 507×         505× 505×                     504× 502×          
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;