redux-conditional
Version:
Make sharing reducers easy by conditionally applying actions to shared Redux reducers.
103 lines (82 loc) • 3.07 kB
JavaScript
var conditionalDefaultSubKey = '__redux_conditional_default_subkey__'; // Symbol('SUB KEY IN CONDITIONAL KEY');
var conditionalKeyReader = function conditionalKeyReader(paths) {
var subKey = arguments.length <= 1 || arguments[1] === undefined ? conditionalDefaultSubKey : arguments[1];
return function (action) {
var fullPath = [];
if (Array.isArray(paths)) {
fullPath = paths;
}
var val = action;
try {
fullPath.reduce(function (prev, cur) {
return val = prev[cur];
}, action);
} catch (err) {
// just don't report error
} finally {
return val && val[subKey];
}
};
};
var conditionalKeyWriter = function conditionalKeyWriter(paths) {
var subKey = arguments.length <= 1 || arguments[1] === undefined ? conditionalDefaultSubKey : arguments[1];
return function (data) {
return function (action) {
var target = action;
if (Array.isArray(paths)) {
target = paths.reduce(function (prev, cur) {
if (prev[cur] === undefined || prev[cur] === null) {
prev[cur] = {};
}
return prev[cur];
}, action);
}
target[subKey] = data;
return action;
};
};
};
var simpleConditionMaker = function simpleConditionMaker(reader) {
return function (data) {
return function (state, action) {
return reader(action) === data;
};
};
};
var simpleConditionalActionCreator = function simpleConditionalActionCreator(paths) {
return function (actionCreator) {
return function (data) {
return function () {
var dataWithKey = data;
if (typeof data !== 'object') {
var _dataWithKey;
dataWithKey = (_dataWithKey = {}, _dataWithKey[conditionalDefaultSubKey] = data, _dataWithKey);
}
var initValue = typeof actionCreator === 'function' ? actionCreator.apply(undefined, arguments) : Object.assign({}, actionCreator);
return Object.keys(dataWithKey).concat(Object.getOwnPropertySymbols(dataWithKey)).reduce(function (action, subKey) {
return conditionalKeyWriter(paths, subKey)(dataWithKey[subKey])(action);
}, initValue);
};
};
};
};
var simpleConditional = function simpleConditional() {
var _ref = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var paths = _ref.paths;
var switches = _ref.switches;
// don't use "actionCreator"
var conditions = { actionCreator: simpleConditionalActionCreator(paths) };
var subKeys = (switches || []).concat([conditionalDefaultSubKey]);
subKeys.forEach(function (subKey) {
var keyWriter = conditionalKeyWriter(paths, subKey);
var keyReader = conditionalKeyReader(paths, subKey);
var exportKey = subKey === conditionalDefaultSubKey ? 'default' : subKey;
conditions[exportKey] = {
conditionMaker: simpleConditionMaker(keyReader),
conditionalKeyWriter: keyWriter,
conditionalKeyReader: keyReader
};
});
return conditions;
};
export { conditionalDefaultSubKey, simpleConditional };