lazy-aggregator
Version:
Creates aggregation wrapper
89 lines (81 loc) • 2.35 kB
JavaScript
;
const add = Symbol.for('add');
const del = Symbol.for('del');
const handler = Symbol.for('handler');
const instances = Symbol.for('instances');
module.exports = class {
/**
* Create lazy-initialized dictionary based on `source` dictionary handled with `fn`
* @constructor lazy-aggregator
* @param {Object.<string, *>} [source={}] - dictionary of configs for `fn` call
* @param {function} [fn=function(key,value){return value}] - function which will be used to create elements in aggregation
* @throws {Error} - if `fn` is not a function
* @example
* import Aggregation from 'lazy-aggregator';
* const fn = (a) => a * 2;
* const source = { el1: 1, el2: 2};
*
* const aggregation = new Aggregation(source, fn);
* aggregation['el1']; // 1
* aggregation.el2; // 2
*/
constructor(source = {}, fn = (key, value) => value) {
this[handler] = fn;
this[instances] = {};
Object
.entries(source)
.forEach(([key, value]) => this[add](key, value));
}
/**
* add element to aggregation
* @param {String} key - first argument to `fn`
* @param {*} [value] - data for `fn` call
* @returns {Object} this
* @example
* import Aggregation from 'lazy-aggregator';
* import {add} from 'lazy-aggregator';
* const fn = (a) => a * 2;
* const source = { el1: 1, el2: 2};
* const aggregation = new Aggregation({}, fn);
* aggregation[add]('newEl', 2);
* aggregation.newEl; // 4
*/
[add](key, value) {
Object.defineProperty(this, key, {
get: () =>
this[instances][key] ?
this[instances][key] :
this[instances][key] = this[handler](key, value)
,
set: function (value) {
this[del](key);
this[add](key, value);
},
configurable: true
});
return this;
}
/**
* delete element from aggregation
* @param {String} key - key of aggregation member to delete
* @returns {Object} this
* @example
* import Aggregation from 'lazy-aggregator';
* import {del} from 'lazy-aggregator';
* const fn = (a) => a * 2;
* const aggregation = new Aggregation({newEl: 3}, fn);
* aggregation[del]('newEl');
* aggregation.newEl; // undefined
*/
[del](key) {
delete this[key];
delete this[instances][key];
return this;
}
/**
* npm install --save lazy-aggregator
* @name Installation
*/
};
module.exports.add = add;
module.exports.del = del;