Skip to content

Instantly share code, notes, and snippets.

@sylvaindesve
Last active June 25, 2024 15:40
Show Gist options
  • Save sylvaindesve/b3293a3c228d114178b52f3267159b1b to your computer and use it in GitHub Desktop.
Save sylvaindesve/b3293a3c228d114178b52f3267159b1b to your computer and use it in GitHub Desktop.
export class StateStore {
// La fonction de réduction de ce store
#reducer;
// L'état courant
#currentState;
// Les "listeners" intéressés par les changements de l'état géré par ce store
#listeners;
constructor(reducer) {
this.#reducer = reducer;
// Initialisation de l'état initial en utilisant la fonction de réduction
this.#currentState = this.#reducer(undefined, { type: "@@INIT" });
this.#listeners = [];
}
getState() {
return this.#currentState;
}
dispatch(action) {
// Utilisation de la fonction de réduction pour obtenir le nouvel état suite à application de l'action
this.#currentState = this.#reducer(this.#currentState, action);
for (const listener of this.#listeners) {
listener(this.#currentState);
}
}
subscribe(listener) {
this.#listeners.push(listener);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment