updux/src/Updux.js

59 lines
1.6 KiB
JavaScript
Raw Normal View History

2021-09-28 22:13:22 +00:00
import moize from 'moize';
import u from '@yanick/updeep';
import { buildInitial } from './buildInitial/index.js';
import { buildActions } from './buildActions/index.js';
2021-09-29 14:21:17 +00:00
import { buildSelectors } from './buildSelectors/index.js';
2021-09-28 22:13:22 +00:00
import { action } from './actions.js';
/**
* @public
* `Updux` is a way to minimize and simplify the boilerplate associated with the
* creation of a `Redux` store. It takes a shorthand configuration
* object, and generates the appropriate reducer, actions, middleware, etc.
* In true `Redux`-like fashion, upduxes can be made of sub-upduxes (`subduxes` for short) for different slices of the root state.
*/
export class Updux {
#initial = {};
#subduxes = {};
#actions = {};
2021-09-29 14:21:17 +00:00
#selectors = {};
2021-09-28 22:13:22 +00:00
constructor(config) {
this.#initial = config.initial ?? {};
this.#subduxes = config.subduxes ?? {};
this.#actions = config.actions ?? {};
2021-09-29 14:21:17 +00:00
this.#selectors = config.selectors ?? {};
2021-09-28 22:13:22 +00:00
}
#memoInitial = moize( buildInitial );
#memoActions = moize(buildActions);
2021-09-29 14:21:17 +00:00
#memoSelectors = moize(buildSelectors);
2021-09-28 22:13:22 +00:00
get initial() {
return this.#memoInitial(this.#initial,this.#subduxes);
}
get actions() {
return this.#memoActions(this.#actions, this.#subduxes);
}
2021-09-29 13:40:02 +00:00
get selectors() {
2021-09-29 14:21:17 +00:00
return this.#memoSelectors(this.#selectors,this.#subduxes);
2021-09-29 13:40:02 +00:00
}
2021-09-28 22:13:22 +00:00
addAction(type, payloadFunc) {
const theAction = action(type,payloadFunc);
this.#actions = u( { [type]: theAction }, this.#actions );
return theAction;
}
2021-09-29 13:40:02 +00:00
addSelector(name, func) {
2021-09-29 14:21:17 +00:00
this.#selectors[name] = func;
return func;
2021-09-29 13:40:02 +00:00
}
2021-09-28 22:13:22 +00:00
}