Skip to content

Instantly share code, notes, and snippets.

@jgcmarins
Forked from kristoferjoseph/store.mjs
Created October 1, 2020 17:16
Show Gist options
  • Select an option

  • Save jgcmarins/8a9f4ea7d0d44dc2bd457eadabfc10cc to your computer and use it in GitHub Desktop.

Select an option

Save jgcmarins/8a9f4ea7d0d44dc2bd457eadabfc10cc to your computer and use it in GitHub Desktop.

Revisions

  1. @kristoferjoseph kristoferjoseph revised this gist Apr 10, 2019. 2 changed files with 0 additions and 2 deletions.
    1 change: 0 additions & 1 deletion listener.mjs
    Original file line number Diff line number Diff line change
    @@ -1 +0,0 @@
    store.subscribe(state => console.log(state))
    1 change: 0 additions & 1 deletion mutator
    Original file line number Diff line number Diff line change
    @@ -1 +0,0 @@
    store.mutate(state => state.thing = { id: 'yolo' })
  2. @kristoferjoseph kristoferjoseph revised this gist Apr 10, 2019. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions listener.mjs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    store.subscribe(state => console.log(state))
  3. @kristoferjoseph kristoferjoseph created this gist Apr 10, 2019.
    1 change: 1 addition & 0 deletions mutator
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    store.mutate(state => state.thing = { id: 'yolo' })
    42 changes: 42 additions & 0 deletions store.mjs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    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