Skip to content

Instantly share code, notes, and snippets.

@jdjkelly
Last active April 30, 2017 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdjkelly/8edb509588de02a0ea226a299755b9ad to your computer and use it in GitHub Desktop.
Save jdjkelly/8edb509588de02a0ea226a299755b9ad to your computer and use it in GitHub Desktop.
ducks.js
export default function createStore(reducer, preloadedState) {
let state = preloadedState
let listeners = []
let dispatching = false
function getState() {
return state
}
function dispatch(action) {
try {
dispatching = true
state = reducer(state, action)
} finally {
dispatching = false
}
for (let i = 0; i < listeners.length; i++) {
const listener = listeners[i]
listener()
}
return action
}
function subscribe(listener) {
listeners.push(listener)
}
// to initialize state
dispatch({})
return {
dispatch,
subscribe,
getState
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment