class State {
  constructor() {
    this.state = {};
    this.callbacks = {};
  }
  get(key) {
    return this.state[key];
  }
  set(key, value) {
    const oldValue = this.state[key];
    this.state[key] = value;
    this._fireCbs(key, value, oldValue);
    return this.state[key];
  }
  sub(key, cb) {
    this.callbacks[key] = this.callbacks[key] || [];
    this.callbacks[key].push(cb);
    if (!this.state[key]) return;
    cb(this.state[key]);
  }
  _fireCbs(key, value, oldValue) {
    this.callbacks[key] = this.callbacks[key] || [];
    this.callbacks[key].forEach(cb => cb(value, oldValue));
  }
}
const state = new State();
window.state = state;

export default state;
