UNPKG

redux-tiles

Version:

Library to create and easily compose redux pieces together in less verbose manner

68 lines 2.8 kB
var __assign = (this && this.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; import { forEachRight, get, isFunction, mapValues } from 'lodash'; /** * @overview create reducer function from the object * @param {Any} initialState – initial state of this part of the store * @param {Object} handlers – object with keys as action types, and * reduce functions to change store as values * @return {Function} – function to act as a reducer */ export function createReducerFromObject(initialState, handlers) { return function reducer(state, action) { if (state === void 0) { state = initialState; } var handler = handlers[action.type]; return typeof handler === 'function' ? handler(state, action) : state; }; } /** * @overview create reducer from the object, with creating reducing functions * @param {Any} initialState – initial state of this part of the store * @param {Object} handlers – object with keys as action types, and * newValues to set at store as values * @return {Function} – function to act as a reducer */ export function createReducer(initialState, handlers) { return createReducerFromObject(initialState, mapValues(handlers, function (value) { return function (state, action) { return reducerCreator({ state: state, action: action, newValue: isFunction(value) ? value(state, action) : value }); }; })); } /** * @overview reducer function, which changes the state with new values * @param {Object} action – reducer action object, with type and payload * @param {Object} state – previous redux state in this branch * @param {Any} newValue – new value to set up in state in corresponding path * @return {Object} – changed reducer */ export function reducerCreator(_a) { var action = _a.action, state = _a.state, newValue = _a.newValue; var path = action.payload.path; var hasNoNestInStore = !path; if (hasNoNestInStore) { return newValue; } var result = {}; var lookupPath; // index stays as it was in original array, so the first // element in the iteration has `i` of the last element! forEachRight(path, function (el, i) { var isLastItem = i === path.length - 1; var newNestedResult = (_a = {}, _a[el] = isLastItem ? newValue : result, _a); lookupPath = path.slice(0, i); var oldState = get(state, lookupPath) || {}; result = __assign({}, oldState, newNestedResult); var _a; }); return __assign({}, state, result); } //# sourceMappingURL=reducer.js.map