redux-tiles
Version:
Library to create and easily compose redux pieces together in less verbose manner
75 lines • 2.95 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;
};
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = require("../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
*/
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, utils_1.mapValues(handlers, function (value) { return function (state, action) {
return reducerCreator({
state: state,
action: action,
newValue: utils_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;
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 = utils_1.get(state, lookupPath) || {};
result = __assign({}, oldState, newNestedResult);
}
return __assign({}, state, result);
var _b;
}
exports.reducerCreator = reducerCreator;
//# sourceMappingURL=reducer.js.map