编写curried javascript函数,可以调用任意次数,这会在最后一次函数调用时返回一个值 [英] Writing a curried javascript function that can be called an arbitrary number of times that returns a value on the very last function call

查看:101
本文介绍了编写curried javascript函数,可以调用任意次数,这会在最后一次函数调用时返回一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写一个编程问题,并要求我编写一个可以用这种方式调用的javascript函数。

 add(1)(2)// 3 
add(1)(2)(3); add(1) // 6
add(1)(2)(3)(4); // 10
add(1)(2)(3)(4)(5); // 15

我在解决问题时遇到的困难是如何使其返回例如,为了使加上(1)(2)起作用,然后 code> add(1)必须返回一个函数,但根据指令 add(1) 1



我假设你可以克服这个问题的一种方法是弄清楚连续多少次 add 函数被调用,但我想不出一种方法来实现这一点。有没有人有任何提示可以指出我正确的方向?



我读过这两篇文章( 1 2 )对函数currying和我了解它们,但我不知道如何处理可变数量的参数时如何进行currying。

解决方案

这不是不可能的,可以使用valueOf()。

  function add(ini​​tNum){var sum = initNum; var callback = function(num){sum + = num;返回回调; }; callback.valueOf = function(){return sum; }; return callback;}; console.log(add(1)(2)== 3); //trueconsole.log(add(1)(1)+1); //3console.log(添加(1)(2)(3).valueOf()); // 6  


I'm currently working on a programming problem in my personal time that asks that I make a javascript function that can be called in this manner.

add(1) // 1
add(1)(2) // 3
add(1)(2)(3); // 6
add(1)(2)(3)(4); // 10
add(1)(2)(3)(4)(5); // 15

What I'm having trouble figuring out is how to make it return a value on the very last call.

For example, in order for add(1)(2) to work, then add(1) has to return a function, but according to the instructions add(1) when called by itself will return 1.

I'm assuming one way you can overcome this is to figure out how many times in succession the add function is being called, but I cannot think of a way to achieve that. Does anyone have any hints that can point me in the right direction?

I've read these two articles (1, 2) on function currying and I understand them, but I'm not sure how to do currying when dealing with a variable number of arguments.

解决方案

It is not impossible, use valueOf().

function add(initNum) {
    var sum = initNum;
    var callback = function (num) {
        sum += num;
        return callback;
    };
    callback.valueOf = function () {
        return sum;
    };
    return callback;
};
console.log(add(1)(2)==3);            //true
console.log(add(1)(1)+1);             //3
console.log(add(1)(2)(3).valueOf());  //6

这篇关于编写curried javascript函数,可以调用任意次数,这会在最后一次函数调用时返回一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆