Created
August 15, 2024 07:49
-
-
Save guiseek/65fa598e39cc2c862a66a04c2d0a14e0 to your computer and use it in GitHub Desktop.
State
This file contains 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
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>>() | |
} |
This file contains 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
export interface Callback<T> { | |
(value: T): void | |
} |
This file contains 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
import {Action, getAction} from './action' | |
export const dispatch = <T>(action: Action<T>) => { | |
for (const callback of getAction(action.type)) { | |
callback(action.value) | |
} | |
} |
This file contains 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
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