@raulpesilva/re-state
Version:
easy way to create a shared state to the entire application
119 lines (91 loc) • 3.2 kB
JavaScript
import _extends from "@babel/runtime/helpers/esm/extends";
import { isFunction } from './utils';
import { getBatch } from './batch';
import { Listener } from './listener';
import { Observer } from './observer';
export var Store = /*#__PURE__*/function () {
function Store() {
this.__store = new Map();
this.__initial_store = new Map();
this.__observer = new Observer();
this.__listener = new Listener();
}
Store.convertStoreToObject = function convertStoreToObject(receivedStore) {
var obj = Object.fromEntries(receivedStore.entries());
return obj;
};
Store.getStoreKeys = function getStoreKeys(store) {
return Array.from(store.keys());
};
var _proto = Store.prototype;
_proto.get = function get(key) {
return this.__store.get(key);
};
_proto.getMany = function getMany(fn) {
if (!isFunction(fn)) {
throw new TypeError('to select a value in the store it is necessary to pass a function - ex: (store) => store.myKey');
}
var objectStore = Store.convertStoreToObject(this.__store);
return fn(objectStore);
};
_proto._set = function _set(key, newValue) {
var hasKey = this.__store.has(key);
if (typeof newValue === 'function') {
var prevValue = this.get(key);
var value = newValue(prevValue);
this.__store.set(key, value);
if (!hasKey) this.setInitialValue(key, value);
} else {
this.__store.set(key, newValue);
if (!hasKey) this.setInitialValue(key, newValue);
}
};
_proto.set = function set(key, newValue) {
var _this = this;
var _Store$convertStoreTo = Store.convertStoreToObject(this.__store),
prevStore = _extends({}, _Store$convertStoreTo);
this._set(key, newValue);
var _Store$convertStoreTo2 = Store.convertStoreToObject(this.__store),
newStore = _extends({}, _Store$convertStoreTo2);
var batch = getBatch();
batch(function () {
_this.notify(key);
_this.notifySelectors(prevStore, newStore);
});
};
_proto.setWithoutNotify = function setWithoutNotify(key, newValue) {
this._set(key, newValue);
};
_proto.setInitialValue = function setInitialValue(key, value) {
this.__initial_store.set(key, value);
};
_proto.has = function has(key) {
return this.__store.has(key);
};
_proto.notifySelectors = function notifySelectors(prevStore, newStore) {
this.__listener.notify(prevStore, newStore);
};
_proto.subscribeSelector = function subscribeSelector(listener) {
return this.__listener.subscribe(listener);
};
_proto.subscribe = function subscribe(key, listener) {
return this.__observer.subscribe(key, listener);
};
_proto.notify = function notify(key) {
this.__observer.notify(key);
};
_proto.reset = function reset() {
var _this2 = this;
this.__store = new Map(this.__initial_store.entries());
var keys = Store.getStoreKeys(this.__store);
var batch = getBatch();
var newStore = Store.convertStoreToObject(this.__store);
batch(function () {
keys.forEach(function (key) {
_this2.notify(key);
_this2.notifySelectors(undefined, newStore);
});
});
};
return Store;
}();