UNPKG

redux-tiles

Version:

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

73 lines 3 kB
"use strict"; 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; }; Object.defineProperty(exports, "__esModule", { value: true }); var lodash_1 = require("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 */ 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; }; } exports.createReducerFromObject = createReducerFromObject; /** * @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 */ function createReducer(initialState, handlers) { return createReducerFromObject(initialState, lodash_1.mapValues(handlers, function (value) { return function (state, action) { return reducerCreator({ state: state, action: action, newValue: lodash_1.isFunction(value) ? value(state, action) : value }); }; })); } exports.createReducer = createReducer; /** * @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 */ 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! lodash_1.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 = lodash_1.get(state, lookupPath) || {}; result = __assign({}, oldState, newNestedResult); var _a; }); return __assign({}, state, result); } exports.reducerCreator = reducerCreator; //# sourceMappingURL=reducer.js.map