@shoutem/redux-composers
Version:
Reducers you can use for composing reducer hierarchy like with combineReducers from redux
56 lines (41 loc) • 2.89 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = mergeReducers;
var _cloneDeep2 = _interopRequireDefault(require("lodash/cloneDeep"));
var _isEmpty2 = _interopRequireDefault(require("lodash/isEmpty"));
var _filter2 = _interopRequireDefault(require("lodash/filter"));
var _merge2 = _interopRequireDefault(require("lodash/merge"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
/**
* Merges the state returned by multiple reducers. Each reducer will receive the
* previous state from the store. The final state will be calculated by performing
* a deep merge of all of the states returned by reducers.
* @param reducers: Order of reducers in array defines the order of merging states
* returned by reducers.
* @returns {Function}: A reducer that invokes every reducer inside the reducers array,
* and constructs a state object or array by deep merging states returned by reducers.
*/
function mergeReducers(reducers) {
var merger = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _merge2["default"];
return function (state, action) {
var nextStates = reducers.map(function (reducer) {
return reducer(state, action);
});
var nextChangedStates = (0, _filter2["default"])(nextStates, function (nextState) {
return nextState !== state && !(0, _isEmpty2["default"])(nextState);
});
if ((0, _isEmpty2["default"])(nextChangedStates)) {
return state;
}
var defaultState = (0, _cloneDeep2["default"])(state);
return merger.apply(void 0, [defaultState].concat(_toConsumableArray(nextChangedStates)));
};
}