tp-store/store.js
2022-03-12 23:38:39 +01:00

68 lines
1.6 KiB
JavaScript

/**
@license
Copyright (c) 2022 trading_peter
This program is available under Apache License Version 2.0
*/
const data = new Map();
const instancesPerKey = new Map();
/**
* # Store
*
* A simple key value store.
*/
export const Store = function(superClass) {
return class extends superClass {
storeSubscribe(keys) {
if (Array.isArray(keys) === false) {
keys = [ keys ];
}
keys.forEach(key => {
let targetProperty;
if (typeof key === 'object') {
targetProperty = key.targetProperty;
key = key.key;
}
this._addInstance(this, key, targetProperty);
});
}
storeUpdated(key, newValue, targetProperty) {
this[targetProperty || key] = newValue;
}
storeWrite(key, value) {
this._writeKey(key, value);
}
_addInstance(instance, key, targetProperty) {
if (instancesPerKey.has(key) === false) {
instancesPerKey.set(key, [ { instance, targetProperty } ]);
} else {
instancesPerKey.get(key).push({ instance, targetProperty });
}
if (data.has(key)) {
this._notifyInstance(instance, key, data.get(key), targetProperty);
}
}
_writeKey(key, value) {
data.set(key, value);
const instances = instancesPerKey.get(key);
if (Array.isArray(instances)) {
instances.forEach(entry => {
this._notifyInstance(entry.instance, key, value, entry.targetProperty);
});
}
}
_notifyInstance(instance, key, value, targetProperty) {
instance.storeUpdated(key, value, targetProperty);
}
};
}