UNPKG

redux-aar

Version:

Actions creator and reducers utilities for redux

99 lines (98 loc) 2.6 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class ReducerLike { constructor(initialState) { this.initialState = initialState; this.subscribedMappers = new Map(); } on(action, mapper) { this.subscribedMappers.set(action.type, mapper); return this; } reduce() { return (state = this.initialState, action) => { if (this.subscribedMappers.has(action.type)) { return this.subscribedMappers.get(action.type)(state, action.payload); } return state; }; } } /** * Creates an action. If the type `T` is specified, it will return `ActionFn<T>` otherwise `EmptyActionFn`. * * ```ts * const reset = createAction('reset'); * const setName = createAction<string>('setName'); * * dispatch(reset()); * dispatch(setName('foobarbaz')); * ``` * * @export * @template T * @param {string} type * @returns {ActionCreatorReturn<T>} */ function createAction(type) { function action(payload) { return { payload, type }; } action.type = type; return action; } exports.createAction = createAction; /** * Creates a reducer. A Reducer handles all mutations to a state when some actions are dispatched. * It takes only one argument which is the initial state to mutate. * To use a created reducer in redux, you have to use the method `reduce` with redux's `combineReducer` function. * * ```ts * import { createReducer } from 'redux-aar'; * * const initialState = () => ({ counter: 0 }); * const reducer = createReducer(initialState()); * * export default reducer.reduce(); * ``` * * @export * @template S * @param {S} initialState * @returns {IReducerLike<InitialState>} */ function createReducer(initialState) { return new ReducerLike(initialState); } exports.createReducer = createReducer; /** * Creates a prefix and returns a `createAction` function. * This is useful if you want to scope all your actions under a given prefix. * Use this if you are writing a domain driven store. * * ```ts * const createAction = prefix('user'); * * const reset = createAction('reset'); * const setName = createAction<string>('setName'); * * reset().type // 'user::reset' * setName('lorem ipsum').type // 'user::setName' * ``` * * @export * @param {string} prefix * @returns {typeof createAction} */ function prefix(prefix) { return (type) => createAction(`${prefix}::${type}`); } exports.prefix = prefix; exports.default = { createAction, createReducer, prefix };