redux-tiles
Version:
Library to create and easily compose redux pieces together in less verbose manner
70 lines • 2.75 kB
JavaScript
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 { get, isFunction, mapValues } from "../utils";
/**
* @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;
var length = path.length;
for (var i = length - 1; i >= 0; i = i - 1) {
var el = path[i];
var isLastItem = i === path.length - 1;
var newNestedResult = (_b = {},
_b[el] = isLastItem ? newValue : result,
_b);
lookupPath = path.slice(0, i);
var oldState = get(state, lookupPath) || {};
result = __assign({}, oldState, newNestedResult);
}
return __assign({}, state, result);
var _b;
}
//# sourceMappingURL=reducer.js.map