【问题标题】:Javascript infinite currying for addition which supports infinite invocations and infinite arguments per invocation? [duplicate]Javascript无限柯里化加法支持无限调用和每次调用的无限参数? [复制]
【发布时间】:2018-11-27 18:04:54
【问题描述】:

在最近的一次采访中,我被要求创建一个在下面的代码 sn-p 中描述的函数

add(2,3,4)(5,6)(7,8); // Should yield 35

从上面的 sn-p 中可以看出,有一个名为“add”的函数可以无限调用,每次调用可以容纳无限参数。最后,它应该返回所有调用中所有参数的总和。

下面是一个部分解决方案,它需要不带参数的最终调用。

/**
 * @description
 * infiniteAdd(2,3)(4,5)(6,7)()
 * Above operation yields 27
 */

function infiniteAdd() {
  // Creating closure for subsequent function invocations
  var prevArgs = Array.prototype.slice.call(arguments);

  return function() {
    var currArgs = Array.prototype.concat.call(prevArgs, Array.prototype.slice.call(arguments));

    if (arguments.length < 1) {
      // if no arguments than calculate sum
      return Array.prototype.reduce.call(currArgs,
        function(acc, curr) {
          return acc + curr;
        }
      );
    }
    
    // Recursively call the main function till no more arguments provided
    return infiniteAdd.apply(null, currArgs);
  }
}

console.log(infiniteAdd(2, 3)(4, 5)(6, 7)());

【问题讨论】:

  • 你有什么问题?
  • 您好,您能澄清一下您的问题吗?这不是用于代码审查或代码编写的服务,因此大多数问题应该描述代码的特定问题,或者您想了解的特定问题。请查看help center,了解有关此网站如何运作以及预期问题的更多信息。

标签: javascript arrays addition


【解决方案1】:

你可以像下面这样实现加法的柯里化功能

function addition(...args) {
  return args.reduce((a, b) => a + b)
}

function parseAdd(fn) {
  var newFn = fn.bind(null);

  function cal(...args) {
    newFn = newFn.bind(null, ...args);
    return cal;
  }

  cal.toString = () => newFn();

  return (...arg) => {
    newFn = fn.bind(null);
    return cal(...arg)
  }
}

var add = parseAdd(addition)

console.log(add(2, 3, 4)(5, 6)(7, 8))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2015-10-12
    相关资源
    最近更新 更多