Skip to content

Instantly share code, notes, and snippets.

@guiseek
Created May 12, 2023 02:46
Show Gist options
  • Save guiseek/41daf10d49792f164587afc47758f9d5 to your computer and use it in GitHub Desktop.
Save guiseek/41daf10d49792f164587afc47758f9d5 to your computer and use it in GitHub Desktop.
Stte handler
let state: any
function handleState<T = unknown>(data: T) {
state = data
// const events: ((state: T) => void)[] = []
const events = new Set<(state: T | null) => void>()
return {
set(newState: T | null) {
if (newState === null) {
state = null
} else {
state = { ...state, ...newState }
}
events.forEach((cb) => cb(state))
return this
},
pick<K extends keyof T>(key: K): T[K] | null {
return state && state[key] ? state[key] : null
},
get() {
return Object.freeze(state)
},
on(cb: (state: T | null) => void) {
events.add(cb)
return this
},
off(cb: (state: T | null) => void) {
events.delete(cb)
return this
},
}
}
export const getStateHandler = <T>(data: T | null = null) => handleState(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment