Newer
Older
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
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;