One way to solve this is by making changes only in the test
code (except for replacing (isNumber, isNumber)
with [isNumber, isNumber]
when calling test).
By creating the function inside test
and returning it to be called via console.log(add(5, 6));
, you can access add
's arguments without any special treatment.
If you use arguments
within a function, you will receive the arguments of that function as an array.
The ...
in func(... arguments);
represents the spread operator, which expands an array in place. For more information, check out spread operator.
function test(precondition, postcondition, func) {
// Extract arguments of func which should be 5 and 6
// This is necessary to verify if isNumber(5) and isNumber(6)
// both return true to meet the precondition
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));
Alternatively, there's a more specific solution that avoids using arguments
and ...
, and doesn't pass an array as precondition
:
function test(precondition, postcondition, func) {
// Extract arguments of func which should be 5 and 6
// This is needed to confirm if isNumber(5) and isNumber(6)
// both return true to satisfy the precondition
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));