Created
February 21, 2024 01:43
-
-
Save josefaidt/6c962ad37986c279f7c4711a114c79a1 to your computer and use it in GitHub Desktop.
quick and simple store example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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