Last active
October 1, 2020 17:16
-
-
Save kristoferjoseph/caef039f3509b64b05c37d88fc3e06a0 to your computer and use it in GitHub Desktop.
store
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const listeners = [] | |
const state = {} | |
let noop = x => x | |
function subscribe (fn) { | |
listeners.push(fn) | |
} | |
function unsubscribe (fn) { | |
listeners.splice(listeners.indexOf(fn), 1) | |
} | |
function mutate (mutation) { | |
mutation = mutation || noop | |
let i = 0 | |
let l = listeners.length | |
let fn | |
mutation(state) | |
for (i; i < l; i++) { | |
fn = listeners[i] | |
fn(state) | |
} | |
} | |
function merge (o, n) { | |
for (let prop in n) { | |
o[prop] = n[prop] | |
} | |
} | |
function store (initialState) { | |
if (initialState) { | |
merge(state, initialState) | |
} | |
return state | |
} | |
store.subscribe = subscribe | |
store.unsubscribe = unsubscribe | |
store.mutate = mutate | |
export default store |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment