Вот решение, которое требует только от вас изменения кода в test
(за исключением вашего вызова для проверки, где я заменил (isNumber, isNumber)
на [isNumber, isNumber]
).
Вы нене нужно делать ничего особенного, чтобы получить доступ к аргументам add
, потому что вы создаете функцию внутри test
и возвращаете ее для вызова console.log(add(5, 6));
.
, используя arguments
внутри любой функциивыдаст аргументы функции в виде массива.
...
в func(... arguments);
- это операция распространения, которая принимает массив и расширяет его на месте.См. оператор распространения .
function test(precondition, postcondition, func) {
// Extract arguments of func which in this case should be 5 and 6
// This is required to check whether isNumber(5) and isNumber(6)
// both return true, so that precondition is met
return function() {
for (const i in arguments) {
const argi = arguments[i];
const precondition_i = precondition[i];
console.log('precondition['+i+'] met: ' + precondition_i(argi));
}
const r = func(... arguments);
console.log('postcondition met: ' + postcondition(r));
return r;
};
}
var add = test([isNumber, isNumber], isNumber, function add(x, y) {return x+y; });
console.log(add(5, 6));
Или менее универсальное решение, которое не использует arguments
и ...
и не передает массив как precondition
:
function test(precondition, postcondition, func) {
// Extract arguments of func which in this case should be 5 and 6
// This is required to check whether isNumber(5) and isNumber(6)
// both return true, so that precondition is met
return function(x, y) {
console.log('precondition met for x: ' + precondition(x));
console.log('precondition met for y: ' + precondition(y));
const r = func(x, y);
console.log('postcondition met: ' + postcondition(r));
return r;
};
}
var add = test(isNumber, isNumber, function add(x, y) {return x+y; });
console.log(add(5, 6));