UNPKG

1.68 kBJavaScriptView Raw
1var slice = Array.prototype.slice;
2
3// our constructor
4function KeyTreeStore() {
5 this.storage = {};
6}
7
8// add an object to the store
9KeyTreeStore.prototype.add = function (keypath, obj) {
10 var arr = this.storage[keypath] || (this.storage[keypath] = []);
11 arr.push(obj);
12};
13
14// remove an object
15KeyTreeStore.prototype.remove = function (obj) {
16 var path, arr;
17 for (path in this.storage) {
18 arr = this.storage[path];
19 arr.some(function (item, index) {
20 if (item === obj) {
21 arr.splice(index, 1);
22 return true;
23 }
24 });
25 }
26};
27
28// get array of all all relevant functions, without keys
29KeyTreeStore.prototype.get = function (keypath) {
30 var res = [];
31 var key;
32
33 for (key in this.storage) {
34 if (!keypath || keypath === key || key.indexOf(keypath + '.') === 0) {
35 res = res.concat(this.storage[key]);
36 }
37 }
38
39 return res;
40};
41
42// get all results that match keypath but still grouped by key
43KeyTreeStore.prototype.getGrouped = function (keypath) {
44 var res = {};
45 var key;
46
47 for (key in this.storage) {
48 if (!keypath || keypath === key || key.indexOf(keypath + '.') === 0) {
49 res[key] = slice.call(this.storage[key]);
50 }
51 }
52
53 return res;
54};
55
56// get all results that match keypath but still grouped by key
57KeyTreeStore.prototype.getAll = function (keypath) {
58 var res = {};
59 var key;
60
61 for (key in this.storage) {
62 if (keypath === key || key.indexOf(keypath + '.') === 0) {
63 res[key] = slice.call(this.storage[key]);
64 }
65 }
66
67 return res;
68};
69
70
71
72module.exports = KeyTreeStore;