Given
const n = 1;
function value(data) {
return data === 1 && data;
}
function compare(data, next) {
return !!(1 == data === next ? next(data) : value(data));
}
function isOne(a, b) {
return !isNaN(a) && b()
}
function result(x, fn) {
return fn ? fn(x) : x(n);
}
we can call result()
result(1, function(data) {return compare(data)}); // true
result(1, function(data) {return compare(value(data))}); // true
result(0, compare.bind(value)); // false
result(compare); // true
result(0, compare); // false
result(1, function(data) {
return isOne(data, compare.bind(null, data, value))
}); // true
With each call pattern resulting in return value of result
being true
.
How can we call value
function as parameter to compare
using Function.prototype.bind
, Function.prototype.call
, Function.prototype.apply
or other approach without explicitly using function() {}
pattern or changing the functions value
, compare
or result
?
For example
// where `value` is called with passed `1` as parameter which
// becomes parameter to `compare` call, which becomes parameter
// to `isOne`, with expected return value of `result` being `true`
result(1, isOne.bind(null, compare.bind(null, value)));
const n = 1;
function value(data) {
console.log("value", data);
return data === 1 && data;
}
function compare(data, next) {
console.log("compare", data, next);
return !!(1 == data === next ? next(data) : value(data));
}
function result(x, fn) {
console.log("result", x, fn);
return fn ? fn(x) : x(n);
}
function isOne(a, b) {
console.log("isOne", a, b);
return !isNaN(a) && b()
}
console.log(result(1, function(data) {
return compare(data, value)
})); // true
console.log(result(0, compare.bind(value))); // false
console.log(result(compare.bind(value))); // true
console.log(result(compare)); // true
console.log(result(1, function(data) {
return isOne(data, compare.bind(null, data, value))
})); // true
// how can we pass `1` to `value`
// expected result: `true`, returns `false`
console.log(result(1, isOne.bind(null, compare.bind(null, value))));
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…