git ssb

1+

clemo / helperjs



Tree: fbad0279dd4439c8eb8da96d385e27acd5755c74

Files: fbad0279dd4439c8eb8da96d385e27acd5755c74 / lib / lib.js

1370 bytesRaw
1import debug from 'debug';
2import Math from './math.js';
3const log = debug('helper:lib:info');
4const error = debug('helper:lib:error');
5export class Lib {
6 constructor() {
7 this.items = [];
8 this._hooks = {};
9 }
10 getById(id) { return this.getArray().filter((item) => (item.id === id))[0]; }
11 getArray() { return this.items.filter((item) => (!item._remove)); }
12 add(item, overwrite = false) {
13 log("add item", item);
14 if ("function" === typeof this._hooks['beforeAdd']) {
15 item = this._hooks['beforeAdd'](item);
16 }
17 if ('undefined' === typeof item.id) {
18 item.id = new Math().uuid();
19 }
20 let existingItem = this.getById(item.id);
21 if ("undefined" !== typeof existingItem) {
22 if (overwrite) {
23 existingItem = item;
24 return existingItem;
25 } else {
26 return log('add duplicate',
27 'item with this id already exist overwrite != true');
28 }
29 } else {
30 this.items.push(item);
31 return item;
32 }
33 }
34
35 setHook(type, fn) {
36 log('setHook', type, fn);
37 this._hooks[type] = fn;
38 }
39
40 remove(id) {
41 log('remove item', id);
42 this.getById(id)._remove = true;
43 }
44
45 each(cb) {
46 let items = this.getArray();
47 for (let i = items.length; i >= 0; i--) {
48 if (items[i] && items[i].id !== null) {
49 cb(items[i]);
50 }
51 }
52 }
53}
54export default Lib;
55

Built with git-ssb-web