Skip to content

Instantly share code, notes, and snippets.

@guiseek
Created August 15, 2024 07:49
Show Gist options
  • Save guiseek/65fa598e39cc2c862a66a04c2d0a14e0 to your computer and use it in GitHub Desktop.
Save guiseek/65fa598e39cc2c862a66a04c2d0a14e0 to your computer and use it in GitHub Desktop.
State
import {Callback} from './callback'
export class Action<T> {
constructor(public type: string, public value: T) {}
}
export const createAction = <T>(type: string) => {
return class extends Action<T> {
constructor(value: T) {
super(type, value)
}
}
}
const actions = new Map<string, Set<Callback<any>>>()
export const setAction = <T>(type: string, callback: Callback<T>) => {
const callbacks = getAction<T>(type)
actions.set(type, callbacks.add(callback))
}
export const getAction = <T>(type: string) => {
return actions.get(type) ?? new Set<Callback<T>>()
}
export interface Callback<T> {
(value: T): void
}
import {Action, getAction} from './action'
export const dispatch = <T>(action: Action<T>) => {
for (const callback of getAction(action.type)) {
callback(action.value)
}
}
import {Callback} from './callback'
import {setAction} from './action'
export const select = <T>(type: string) => {
return (callback: Callback<T>) => {
setAction(type, callback)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment