确定如何在关闭JavaScript中调用该函数 [英] Identify how the function has been called in closure javascript
问题描述
函数multiply(a,b){
return a * b;
$ b 现在这个函数可能以不同的方式调用这个问题,比如
p> multiply(4,5);
乘(4)(5);
乘(4)(5)(6);
我知道我们必须为第二个乘法(4)(5)关闭apporach。 (b,b){
函数乘法(a,b){
返回函数(b){
返回a * b;
$ b现在如果它的乘法函数被调用3个参数相乘(4)(5)(6)。我如何确定函数的调用方式,以及如何为所有输入编写一个通用解决方案。
任何帮助都是值得赞赏的。谢谢
解决方案
为了拥有无限制的callchain,你需要一些js技巧:
函数multiply(... args){
//通过使用一些递归类似的东西来使链无穷无尽:
const func =(... args2) =>乘(参数... args,... args2);
//链端点:$ b $ b func.valueOf = function(){
return args.reduce((a,b)=> a * b);
};
返回func;
$ b 这种可变的柯里化的问题是它的无穷大,所以theres(通常)无法结束它。
multiply(1)// func:/
然而,在JavaScript中,可能会将方法分配给函数,所以我们可以在调用方法而不是函数来结束链时轻松地完成一些操作。 b
$ b
multiply(1)(2)(3).valueOf()
所以你可以简单地做:
console.log(
+乘(1,2,3)(4)(5),
+乘(1,2)
);
+等于 valueOf ,因此需要结束链,但是这个对 valueOf 的调用可以通过javascript中的许多操作(所有数学运算,如 - * /)推断出来。
Recently i faced one problem in hackerrank which has to calculate multiplication operation and has to return the answer. For example
function multiply(a,b) {
return a*b;
}
Now here is the problem the function might call in different ways such as
multiply(4,5);
multiply(4)(5);
multiply(4)(5)(6);
I know we have to closure apporach for the second one which is multiply(4)(5). I had written code for that
function multiply(a,b) {
return function(b) {
return a*b;
}
}
Now what if its been multiply function has been called with 3 arguments multiply(4)(5)(6). How can i identify how the function has been called and how can i write a common solution for all the inputs.
Any help is appreciated. Thanks
解决方案 To have an unlimited callchain you need some js trick:
function multiply(...args){
//make the chain endless through using some recursive like stuff:
const func = (...args2) => multiply(...args,...args2);
//the chains endpoint:
func.valueOf = function(){
return args.reduce((a,b) => a*b);
};
return func;
}
The problem of such variable currying is that its infinite, so theres ( usually ) no way to end it.
multiply(1) // func :/
However in javascript its possible to assign methods to functions so we can easily somewhen call the method instead of the function to end the chain:
multiply(1)(2)(3).valueOf()
So you can simply do:
console.log(
+multiply(1,2,3)(4)(5),
+multiply(1,2)
);
The + is equal to valueOf and is therefore neccessary to end the chain, however this call to valueOf is inferred by many operations in javascript ( all math operations like - * /).
这篇关于确定如何在关闭JavaScript中调用该函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!