Skip to content

Instantly share code, notes, and snippets.

@mnpenner
Created November 16, 2017 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mnpenner/1216bd96ba7d8430fa804781f9be0da9 to your computer and use it in GitHub Desktop.
Save mnpenner/1216bd96ba7d8430fa804781f9be0da9 to your computer and use it in GitHub Desktop.
export default class Store {
constructor() {
this.subscriptions = Object.create(null);
this.data = Object.create(null);
// this.counter = 0;
this._fireSubscriptions = debounce(context => {
for(let [k,v] of Object.entries(this.subscriptions)) {
let newValue = getValue(this.data, v[0]);
if(!Object.is(v[2],newValue)) {
v[1](newValue, v[2], context);
v[2] = newValue;
}
}
const elapsed = performance.now() - start;
});
}
subscribe(path, callback) {
path = toPath(path);
let key = shortid();
this.subscriptions[key] = [path,callback,getValue(this.data,path)];
const unsub = () => {
delete this.subscriptions[key];
};
unsub.key = key;
return unsub;
}
get(path) {
return getValue(this.data, path);
}
unset(path) {
if(unset(this.data, path)) {
this._fireSubscriptions();
}
}
set(path, value, context) {
path = toPath(path);
let oldValue = getValue(this.data, path);
if(typeof value === 'function') {
value = value(oldValue);
}
if(Object.is(oldValue, value)) return;
setValue(this.data, path, value);
this._fireSubscriptions(context);
}
toJSON() {
// TODO: strip undefined values?
return this.data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment