Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

javascript - How to call function that is parameter to Function.prototype.bind with value passed as parameter to Function.prototype.bind

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...