updux/src/Updux.ts

44 lines
1.1 KiB
TypeScript
Raw Normal View History

2022-08-25 14:22:32 +00:00
import R from 'remeda';
2022-08-25 01:37:31 +00:00
2022-08-25 14:22:32 +00:00
/**
* Configuration object typically passed to the constructor of the class Updux.
*/
2022-08-25 14:51:07 +00:00
export interface UpduxConfig<TState = any, TSubduxes = {}> {
2022-08-25 14:22:32 +00:00
/**
* Local initial state.
* @default {}
*/
initial?: TState;
/**
* Subduxes to be merged to this dux.
*/
subduxes?: TSubduxes;
}
type StateOf<D> = D extends { initial: infer I } ? I : unknown;
2022-08-25 14:51:07 +00:00
export type DuxStateSubduxes<C extends {}> = keyof C extends never
? unknown
: { [K in keyof C]: StateOf<C[K]> };
2022-08-25 14:22:32 +00:00
export class Updux<TState extends any = {}, TSubduxes = {}> {
2022-08-25 14:51:07 +00:00
#localInitial: any = {};
2022-08-25 14:22:32 +00:00
#subduxes;
constructor(config: UpduxConfig<TState, TSubduxes>) {
this.#localInitial = config.initial ?? {};
this.#subduxes = config.subduxes ?? {};
}
get initial(): TState & DuxStateSubduxes<TSubduxes> {
2022-08-25 14:51:07 +00:00
if (Object.keys(this.#subduxes).length === 0) return this.#localInitial;
2022-08-25 14:22:32 +00:00
2022-08-25 14:51:07 +00:00
return Object.assign(
{},
this.#localInitial,
R.mapValues(this.#subduxes, ({ initial }) => initial),
);
2022-08-25 14:22:32 +00:00
}
2022-08-25 01:37:31 +00:00
}