Skip to content

Instantly share code, notes, and snippets.

@esco
Last active November 3, 2020 14:53
Show Gist options
  • Save esco/eb224ac20dcc6721f6d0b663d3fbe6b1 to your computer and use it in GitHub Desktop.
Save esco/eb224ac20dcc6721f6d0b663d3fbe6b1 to your computer and use it in GitHub Desktop.

Revisions

  1. esco revised this gist Nov 3, 2020. 1 changed file with 3 additions and 1 deletion.
    4 changes: 3 additions & 1 deletion store.js
    Original file line number Diff line number Diff line change
    @@ -9,7 +9,9 @@ function createStore(reducer, preloadedState) {

    function subscribe(listener) {
    let id = idPool.pop()
    idPool.push(id + 1)
    if (!idPool.length) {
    idPool.push(id + 1)
    }
    listeners.set(id, listener)
    return function unsubscribe() {
    listeners.delete(id)
  2. esco created this gist Nov 3, 2020.
    30 changes: 30 additions & 0 deletions store.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    function createStore(reducer, preloadedState) {
    let state = preloadedState
    const idPool = [0]
    const listeners = new Map()

    function getState() {
    return state
    }

    function subscribe(listener) {
    let id = idPool.pop()
    idPool.push(id + 1)
    listeners.set(id, listener)
    return function unsubscribe() {
    listeners.delete(id)
    idPool.push(id)
    }
    }

    function dispatch(action) {
    state = reducer(state, action)
    for ([_, listener] of listeners) {
    listener()
    }
    }

    dispatch({ type: '@@redux/INIT' })

    return { dispatch, subscribe, getState }
    }