UNPKG

juliette

Version:
40 lines 1.65 kB
import { BehaviorSubject, Subject } from 'rxjs'; import { distinctUntilChanged, map } from 'rxjs/operators'; import { log } from './log'; import { deepFreeze } from './helpers'; export class Store { constructor(initialState, devMode) { this.devMode = devMode; this.handlers = new Subject(); this.handlers$ = this.handlers.asObservable(); if (devMode) deepFreeze(initialState); this.state = new BehaviorSubject(initialState); this.state$ = this.state.asObservable(); } dispatch(handler) { if (handler.reducer && handler.featureKey) { const currentState = this.state.value[handler.featureKey]; if (this.devMode) deepFreeze(currentState); this.state.next(Object.assign(Object.assign({}, this.state.value), { [handler.featureKey]: handler.reducer(currentState, handler.payload) })); } this.handlers.next(handler); } select(keyOrSelector) { const mapFn = typeof keyOrSelector === 'function' ? keyOrSelector : (state) => state[keyOrSelector]; return this.state$.pipe(map(mapFn), distinctUntilChanged()); } addFeatureState(featureKey, initialState) { if (this.devMode) deepFreeze(initialState); this.state.next(Object.assign(Object.assign({}, this.state.value), { [featureKey]: initialState })); } } export const createStore = (initialState, devMode = false) => { const store = new Store(initialState, devMode); if (devMode) log(store); return store; }; //# sourceMappingURL=store.js.map