Skip to content

Instantly share code, notes, and snippets.

@jabney
Last active February 15, 2024 17:03
Show Gist options
  • Save jabney/f135c8377213d6f9a008d3d55db5fd9e to your computer and use it in GitHub Desktop.
Save jabney/f135c8377213d6f9a008d3d55db5fd9e to your computer and use it in GitHub Desktop.
micro-redux: a minimal implementation of Redux createStore, with thunkish behavior added in
/**
* Minimal implementation of Redux createStore, with thunkish behavior.
*/
import subject from './micro-subject' // see micro-subject.js gist
/**
* @template T
* @typedef {import('./subject').Subject<T>} Subject
*/
/**
* @param {(state: any, action: any) => any} reducer
* @param {any} [initial]
*/
export const createStore = (reducer, initial) => {
/**
* @type {Subject<void>}
*/
const _subject = subject()
let state = initial !== undefined ? initial : reducer(undefined, {})
return {
/**
* Dispatch an action to update the store.
*/
dispatch(action) {
// Built-in 'thunk' functionality.
if (typeof action === 'function') {
action(this.dispatch.bind(this), this.getState)
} else {
state = reducer(state, action)
_subject.notify()
}
},
/**
* Get the store's current state.
*/
getState() {
return state
},
/**
* Receive notifications when the store is updated.
*
* @param {() => void} observer
*
* @returns {() => void} unsubscribe function
*/
subscribe(observer) {
const unsubscribe = _subject.subscribe(observer)
_subject.notify()
return unsubscribe
}
}
}
export default createStore
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment