Skip to content

Instantly share code, notes, and snippets.

@josefaidt
Created February 21, 2024 01:43
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 josefaidt/6c962ad37986c279f7c4711a114c79a1 to your computer and use it in GitHub Desktop.
Save josefaidt/6c962ad37986c279f7c4711a114c79a1 to your computer and use it in GitHub Desktop.
quick and simple store example
function createStore<T = unknown>(initial?: T) {
type Subscriber = (state: T) => void
let previous: T
let current: T
let _subscriber: Subscriber
if (initial) current = initial
const update = (state: T) => {
previous = current
current = state
_subscriber(current)
}
const get = () => current
const set = (state: T) => update(state)
const subscribe = (subscriber: Subscriber) => {
_subscriber = subscriber
}
return {
get,
set,
subscribe,
}
}
const store = createStore(0)
store.subscribe(console.log)
store.set(2)
store.set(3)
setInterval(() => store.set(store.get() + 1), 300)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment