UNPKG

key-tree-store

Version:

Simple tool for storing/retrieving objects events based hierarchical keypaths.

86 lines (70 loc) 2.18 kB
var slice = Array.prototype.slice; // our constructor function KeyTreeStore(options) { options = options || {}; if (typeof options !== 'object') { throw new TypeError('Options must be an object'); } var DEFAULT_SEPARATOR = '.'; this.storage = {}; this.separator = options.separator || DEFAULT_SEPARATOR; } // add an object to the store KeyTreeStore.prototype.add = function (keypath, obj) { var arr = this.storage[keypath] || (this.storage[keypath] = []); arr.push(obj); }; // remove an object KeyTreeStore.prototype.remove = function (obj) { var path, arr; for (path in this.storage) { arr = this.storage[path]; arr.some(function (item, index) { if (item === obj) { arr.splice(index, 1); return true; } }); } }; // get array of all all relevant functions, without keys KeyTreeStore.prototype.get = function (keypath) { var res = []; var key; for (key in this.storage) { if (!keypath || keypath === key || key.indexOf(keypath + this.separator) === 0) { res = res.concat(this.storage[key]); } } return res; }; // get all results that match keypath but still grouped by key KeyTreeStore.prototype.getGrouped = function (keypath) { var res = {}; var key; for (key in this.storage) { if (!keypath || keypath === key || key.indexOf(keypath + this.separator) === 0) { res[key] = slice.call(this.storage[key]); } } return res; }; // get all results that match keypath but still grouped by key KeyTreeStore.prototype.getAll = function (keypath) { var res = {}; var key; for (key in this.storage) { if (keypath === key || key.indexOf(keypath + this.separator) === 0) { res[key] = slice.call(this.storage[key]); } } return res; }; // run all matches with optional context KeyTreeStore.prototype.run = function (keypath, context) { var args = slice.call(arguments, 2); this.get(keypath).forEach(function (fn) { fn.apply(context || this, args); }); }; module.exports = KeyTreeStore;