react-component-decorators
Version:
React decorators, magic.
111 lines (91 loc) • 2.97 kB
JavaScript
;
exports.__esModule = true;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.default = validateOn;
/* eslint 'no-for-each/no-for-each': 2 */
/**
* @return {boolean}
*/
function validateOn(conditions, valuesToCheck) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var defaultOptions = {
satisfied: false,
debug: false,
exists: true,
thisArg: false,
// example conditions: {
// state: (val) => true,
// props: {
// eh: false,
// }
// }
conditions: conditions
};
options = Object.assign(defaultOptions, options);
var satisfied = options.satisfied;
var conds = options.conditions;
if (conds.conditions) conds = conds.conditions;
if (conds.conditions) conds = conds.conditions;
if (!conds) {
console.error({ conditions: conditions, valuesToCheck: valuesToCheck, options: options });
throw new Error('@validate on requires .conditions');
}
if (options.exists && !valuesToCheck) {
return false;
}
var condIsObj = false;
var condKeys = conds;
if ((typeof conds === 'undefined' ? 'undefined' : _typeof(conds)) === 'object') {
condKeys = Object.keys(conds);
condIsObj = true;
}
// loop our condition
for (var ii = 0, condsLen = condKeys.length; ii < condsLen; ii++) {
var condProp = condKeys[ii];
// if (condIsObj)
// -----
// loop the values, for the condition at the current condition property
// @example: {
// state: {
// loading: (loading) => loading === false,
// }
// }
var isObj = false;
var keys = Object.keys(conds[condProp]);
var condsForProp = conds[condProp];
// @example:
// `state`
var vals = valuesToCheck[condProp];
// loop through each property of the condition
// would be `.loading` from ^
for (var i = 0, len = keys.length; i < len; i++) {
var key = keys[i];
// @example:
// this.state.loading
var val = vals[key];
// so we can loop through objects or array
// if (isObj) val = state[key]
var condition = condsForProp[key];
if (!condition) {
if (options.debug) {
console.debug('@validateOn had no condition fn for ', condition);
}
} else if (typeof condition == 'boolean') {
// if (val === condition)
if (val) {
satisfied = true;
}
} else if (typeof condition === 'function') {
if (options.thisArg) {
if (!condition.call(this, val)) {
satisfied = false;
}
} else if (!condition(val)) {
satisfied = false;
}
}
}
}
return satisfied;
}
module.exports = exports['default'];