如何执行一项功能(正常还是已执行)并产生相同的结果?

时间:2019-05-29 12:25:55

标签: javascript function currying

一个multiply函数的主体是什么,如果以下面两种方式执行,将产生相同的结果。因此,调用multiply(2,4)multiply(2)(4)会输出8吗?

4 个答案:

答案 0 :(得分:1)

您可以检查是否通过了第二个arg。

function multiply(a,b){
  if(b === undefined){
    return function(b){
      return a * b;
    }
  }
  return a * b
}

console.log(multiply(2,4))
console.log(multiply(2)(4))

答案 1 :(得分:0)

非常简单-检查第二个参数是否存在,并相应地修改返回值:

const multiply = (a, b) => b ? a * b : c => a * c;
console.log(multiply(2, 3));
console.log(multiply(2)(4));

这也可以很简单地扩展为接受三个参数:

const multiply = (a, b, c) => c ? a * b * c : (b ? (d => a * b * d) : (d, e) => a ? d * e : f => d * f);
console.log(multiply(2, 3, 4));
console.log(multiply(2, 5)(3));
console.log(multiply(2)(6, 3));

答案 2 :(得分:0)

每当您具有提示功能时,就需要某种方式来结束该计算,就像需要递归的基本情况一样。结束条件可以是

(1)自变量的数量,例如在这种情况下为2:

  const curry = (fn, n) => {
     const c = (...args) => (...args2) => args.length + args.length >= n ? fn(...args, ...args2) : c(...args, ...args2);
     return c();
  };

  const add = curry((a, b) => a + b, 2);

(1b)确保也可以从函数签名中得出:

 const curry = (fn, ...keep) => (...args) => keep.length + args.length >= fn.length ? fn(...keep,  ...args) : curry(fn, ...keep, ...args);

 const add = curry((a, b) => a + b);

(2)最后的空函数调用,例如add(1, 2)()add(1)(2)()

   const curry = fn => (...args) => (...args2) => args2.length ? curry(fn)(...args, ...args2) : fn(...args, ...args2);

  const add = curry((a, b) => a + b);

(3)最后进行一些类型转换,以触发要计算的结果,例如+add(1, 2)+add(1)(2)

  const curry = (fn, ...keep) => {
    const c = (...args) => curry(fn, ...keep, ...args);
    c.valueOf = () => fn(...keep);
    return c;
  };

  const add = curry((a, b) => a + b);

答案 3 :(得分:0)

const multiply = (a,b) => !b ? (b) => a * b : a * b; 
console.log(multiply(2, 4))
console.log(multiply(2)(4))