(initialState)
| 5 | |
| 6 | |
| 7 | export const createStore = (initialState) => { |
| 8 | let state = initialState; |
| 9 | |
| 10 | const listeners = new Set(); |
| 11 | const gen = flatPathGenerator('/'); |
| 12 | const pathListeners = new Set(); |
| 13 | |
| 14 | // Exposed functions |
| 15 | // Don't attempt to manipulate the state directly. |
| 16 | const getState = () => state; |
| 17 | const setState = (nextState) => { |
| 18 | const prevState = state; |
| 19 | state = _.clone(nextState); |
| 20 | |
| 21 | if (isValueEqual(state, prevState)) return; |
| 22 | |
| 23 | listeners.forEach((listener) => { |
| 24 | listener(); |
| 25 | }); |
| 26 | |
| 27 | const changeMemo = new Map(); |
| 28 | |
| 29 | pathListeners.forEach((pathListener) => { |
| 30 | const [ path, listener ] = pathListener; |
| 31 | const flatPath = gen.flatPath(path); |
| 32 | |
| 33 | if (!changeMemo.has(flatPath)) { |
| 34 | const pathNextValue = |
| 35 | flatPath == '' ? nextState : _.get(nextState, path, undefined); |
| 36 | const pathPrevValue = |
| 37 | flatPath == '' ? prevState : _.get(prevState, path, undefined); |
| 38 | |
| 39 | changeMemo.set(flatPath, [ |
| 40 | isValueEqual(pathNextValue, pathPrevValue), |
| 41 | pathNextValue, |
| 42 | pathPrevValue, |
| 43 | ]); |
| 44 | } |
| 45 | |
| 46 | const [isSame, pathNextValue, pathPrevValue] = changeMemo.get(flatPath); |
| 47 | |
| 48 | if (!isSame) { |
| 49 | listener(pathNextValue, pathPrevValue); |
| 50 | } |
| 51 | }); |
| 52 | }; |
| 53 | const get = (path = []) => (_.get(state, path)); |
| 54 | const set = (arg) => { |
| 55 | let nextState = _.isFunction(arg) ? arg(_.cloneDeep(state)) : arg; |
| 56 | setState(nextState); |
| 57 | }; |
| 58 | const subscribe = (listener) => { |
| 59 | listeners.add(listener); |
| 60 | return () => listeners.delete(listener); |
| 61 | }; |
| 62 | const subscribeForPath = (path, listner) => { |
| 63 | const data = [path, listner]; |
| 64 |
no test coverage detected