You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
46 lines
1.4 KiB
JavaScript
46 lines
1.4 KiB
JavaScript
"use strict";
|
|
|
|
const generateValidator = require("./generate-validator");
|
|
|
|
module.exports = function guardFunction(args, returnType, func) {
|
|
let rules = args.map((arg) => {
|
|
return generateValidator(arg);
|
|
});
|
|
|
|
let returnValueValidator = generateValidator(returnType);
|
|
|
|
let guardedFunction = function (...params) {
|
|
let paramsWithDefaults = new Array(params.length);
|
|
|
|
/* TODO: Can this be made faster by manually incrementing the index outside of the loop, or even by using forEach? ref https://jsperf.com/for-of-vs-foreach-with-index */
|
|
for (let [i, rule] of rules.entries()) {
|
|
let validatorResult = rule.call(this, params[i]);
|
|
|
|
if (validatorResult === true) {
|
|
paramsWithDefaults[i] = params[i];
|
|
} else if (validatorResult._default !== undefined) {
|
|
paramsWithDefaults[i] = validatorResult._default;
|
|
} else {
|
|
throw validatorResult;
|
|
}
|
|
}
|
|
|
|
let returnValue = func.apply(this, paramsWithDefaults);
|
|
let returnValueValidatorResult = returnValueValidator.call(this, returnValue);
|
|
|
|
if (returnValueValidatorResult === true) {
|
|
return returnValue;
|
|
} else if (returnValueValidatorResult._default !== undefined) {
|
|
return returnValueValidatorResult.default;
|
|
} else {
|
|
throw returnValueValidatorResult;
|
|
}
|
|
};
|
|
|
|
guardedFunction._guardedArgs = args;
|
|
guardedFunction._guardedReturnType = returnType;
|
|
guardedFunction._guardedFunction = func;
|
|
|
|
return guardedFunction;
|
|
};
|