Last active
June 25, 2024 15:40
-
-
Save sylvaindesve/b3293a3c228d114178b52f3267159b1b to your computer and use it in GitHub Desktop.
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 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