如何使var a = add(2)(3); // 5工作?

时间:2022-11-29 23:25:41

I want to make this syntax possible:

我想使这种语法成为可能:

var a = add(2)(3); //5

based on what I read at http://dmitry.baranovskiy.com/post/31797647

根据我在http://dmitry.baranovskiy.com/post/31797647上读到的内容

I've got no clue how to make it possible.

我不知道如何使它成为可能。

17 个解决方案

#1


74  

You need add to be a function that takes an argument and returns a function that takes an argument that adds the argument to add and itself.

您需要添加为一个函数,该函数接受一个参数并返回一个函数,该函数接受一个参数,该参数将参数添加到add及其自身。

var add = function(x) {
    return function(y) { return x + y; };
}

#2


29  

function add(x) {
    return function(y) {
        return x + y;
    };
}

Ah, the beauty of JavaScript

啊,JavaScript的美丽

This syntax is pretty neat as well

这个语法也非常简洁

function add(x) {
    return function(y) {
        if (typeof y !== 'undefined') {
            x = x + y;
            return arguments.callee;
        } else {
            return x;
        }
    };
}
add(1)(2)(3)(); //6
add(1)(1)(1)(1)(1)(1)(); //6

#3


14  

function add(x){
  return function(y){
    return x+y
  }
}

First-class functions and closures do the job.

一流的功能和闭包完成了这项工作。

#4


8  

try this will help you in two ways add(2)(3) and add(2,3)

试试这会帮助你以两种方式添加(2)(3)和添加(2,3)

1.)

 function add(a){ return function (b){return a+b;} }

    add(2)(3) // 5

2.)

function add(a,b){
        var ddd = function (b){return a+b;};
        if(typeof b =='undefined'){
            return ddd;
        }else{
            return ddd(b);
        }
    }

add(2)(3) // 5
add(2,3) // 5

#5


8  

function add(n) {
  sum = n;
  const proxy = new Proxy(function a () {}, {
    get (obj, key) {
      return () => sum;
    },
    apply (receiver, ...args) {
      sum += args[1][0];
      return proxy;
    },
  });
  return proxy
}

Works for everything and doesn't need the final () at the end of the function like some other solutions.

适用于所有内容,并且不需要函数末尾的final(),就像其他解决方案一样。

console.log(add(1)(2)(3)(10));    // 16
console.log(add(10)(10));         // 20

#6


6  

ES6 syntax makes this nice and simple:

ES6语法使这很简单:

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

console.log(add(2, 5)); 
// output: 7

const add2 = a => b => a + b;

console.log(add2(2)(5));
// output: 7

#7


3  

in addition to what's already said, here's a solution with generic currying (based on http://github.com/sstephenson/prototype/blob/master/src/lang/function.js#L180)

除了已经说过的,这里是一个通用currying的解决方案(基于http://github.com/sstephenson/prototype/blob/master/src/lang/function.js#L180)

Function.prototype.curry = function() {
    if (!arguments.length) return this;
    var __method = this, args = [].slice.call(arguments, 0);
    return function() {
      return __method.apply(this, [].concat(
        [].slice.call(args, 0),
        [].slice.call(arguments, 0)));
   }
}


add = function(x) {
    return (function (x, y) { return x + y }).curry(x)
}

console.log(add(2)(3))

#8


3  

Concept of CLOSURES can be used in this case.
The function "add" returns another function. The function being returned can access the variable in the parent scope (in this case variable a).

在这种情况下可以使用CLOSURES的概念。函数“add”返回另一个函数。返回的函数可以访问父作用域中的变量(在本例中为变量a)。

function add(a){

    return function(b){
        console.log(a + b);
    }

}


add(2)(3);

Here is a link to understand closures http://www.w3schools.com/js/js_function_closures.asp

这是一个了解闭包的链接http://www.w3schools.com/js/js_function_closures.asp

#9


3  

It's about JS curring and a little strict with valueOf:

这是关于JS curring和有点严格的valueOf:

function add(n){
  var addNext = function(x) {
    return add(n + x);
  };

  addNext.valueOf = function() {
    return n;
  };

  return addNext;
}

console.log(add(1)(2)(3)==6);//true
console.log(add(1)(2)(3)(4)==10);//true

It works like a charm with an unlimited adding chain!!

它就像一个无限添加链的魅力!

#10


2  

This is a generalized solution which will solve add(2,3)(), add(2)(3)() or any combination like add(2,1,3)(1)(1)(2,3)(4)(4,1,1)(). Please note that few security checks are not done and it can be optimized further.

这是一个通用的解决方案,它将解决add(2,3)(),add(2)(3)()或任何组合,如add(2,1,3)(1)(1)(2,3)( 4)(4,1,1)()。请注意,很少进行安全检查,可以进一步优化。

function add() {
	var total = 0;

	function sum(){
		if( arguments.length ){
			var arr = Array.prototype.slice.call(arguments).sort();
			total = total + arrayAdder(arr);
			return sum;
		}
		else{
			return total;
		}
	}

	if(arguments.length) {
		var arr1 = Array.prototype.slice.call(arguments).sort();
		var mytotal = arrayAdder(arr1);
		return sum(mytotal);
	}else{
		return sum();
	}

	function arrayAdder(arr){
		var x = 0;
		for (var i = 0; i < arr.length; i++) {
			x = x + arr[i];
		};
		return x;
	}
}
add(2,3)(1)(1)(1,2,3)();

#11


1  

function add(a, b){
 return a && b ? a+b : function(c){return a+c;}
}

console.log(add(2, 3));
console.log(add(2)(3));

#12


1  

This will handle both

这将处理两者

add(2,3) // 5

or

add(2)(3) // 5

This is an ES6 curry example...

这是ES6咖喱的例子......

const add = (a, b) => (b || b === 0) ? a + b : (b) => a + b;

#13


1  

With ES6 spread ... operator and .reduce function. With that variant you will get chaining syntax but last call () is required here because function is always returned:

使用ES6传播...运算符和.reduce函数。使用该变体,您将获得链接语法,但此处需要最后一次调用(),因为始终返回函数:

function add(...args) {
    if (!args.length) return 0;
    const result = args.reduce((accumulator, value) => accumulator + value, 0);
    const sum = (...innerArgs) => {
        if (innerArgs.length === 0) return result;
        return add(...args, ...innerArgs);    
    };
    return sum;
}




// it's just for fiddle output
document.getElementById('output').innerHTML = `
<br><br>add() === 0: ${add() === 0 ? 'true' : 'false, res=' + add()}
<br><br>add(1)(2)() === 3: ${add(1)(2)() === 3 ? 'true' : 'false, res=' + add(1)(2)()}
<br><br>add(1,2)() === 3: ${add(1,2)() === 3 ? 'true' : 'false, res=' + add(1,2)()}
<br><br>add(1)(1,1)() === 3: ${add(1)(1,1)() === 3 ? 'true' : 'false, res=' + add(1)(1,1)()}
<br><br>add(2,3)(1)(1)(1,2,3)() === 13: ${add(2,3)(1)(1)(1,2,3)() === 13 ? 'true' : 'false, res=' + add(2,3)(1)(1)(1,2,3)()}
`;
<div id='output'></div>

#14


0  

function add() { var sum = 0;

function add(){var sum = 0;

    function add() {
        for (var i=0; i<arguments.length; i++) {
            sum += Number(arguments[i]);
        }
        return add;
    }
    add.valueOf = function valueOf(){
        return parseInt(sum);
    };
    return add.apply(null,arguments);
}

// ...

console.log(add() + 0);               // 0
console.log(add(1) + 0);/*                 // 1
console.log(add(1,2) + 0);               // 3

#15


0  

function A(a){
  return function B(b){
      return a+b;
  }
}

I found a nice explanation for this type of method. It is known as Syntax of Closures

我找到了这种方法的一个很好的解释。它被称为闭包语法

please refer this link Syntax of Closures

请参阅此链接语法闭包

#16


0  

const add = a => b => b ? add(a+b) : a;

console.log(add(1)(2)(3)());

Or (`${a} ${b}`) for strings.

或者(`$ {a} $ {b}`)表示字符串。

#17


-1  

function add () {
    var args = Array.prototype.slice.call(arguments);
 
    var fn = function () {
        var arg_fn = Array.prototype.slice.call(arguments);
        return add.apply(null, args.concat(arg_fn));
    }
 
    fn.valueOf = function () {
        return args.reduce(function(a, b) {
            return a + b;
        })
    }
 
    return fn;
}

console.log(add(1));
console.log(add(1)(2));
console.log(add(1)(2)(5));

from http://www.cnblogs.com/coco1s/p/6509141.html

#1


74  

You need add to be a function that takes an argument and returns a function that takes an argument that adds the argument to add and itself.

您需要添加为一个函数,该函数接受一个参数并返回一个函数,该函数接受一个参数,该参数将参数添加到add及其自身。

var add = function(x) {
    return function(y) { return x + y; };
}

#2


29  

function add(x) {
    return function(y) {
        return x + y;
    };
}

Ah, the beauty of JavaScript

啊,JavaScript的美丽

This syntax is pretty neat as well

这个语法也非常简洁

function add(x) {
    return function(y) {
        if (typeof y !== 'undefined') {
            x = x + y;
            return arguments.callee;
        } else {
            return x;
        }
    };
}
add(1)(2)(3)(); //6
add(1)(1)(1)(1)(1)(1)(); //6

#3


14  

function add(x){
  return function(y){
    return x+y
  }
}

First-class functions and closures do the job.

一流的功能和闭包完成了这项工作。

#4


8  

try this will help you in two ways add(2)(3) and add(2,3)

试试这会帮助你以两种方式添加(2)(3)和添加(2,3)

1.)

 function add(a){ return function (b){return a+b;} }

    add(2)(3) // 5

2.)

function add(a,b){
        var ddd = function (b){return a+b;};
        if(typeof b =='undefined'){
            return ddd;
        }else{
            return ddd(b);
        }
    }

add(2)(3) // 5
add(2,3) // 5

#5


8  

function add(n) {
  sum = n;
  const proxy = new Proxy(function a () {}, {
    get (obj, key) {
      return () => sum;
    },
    apply (receiver, ...args) {
      sum += args[1][0];
      return proxy;
    },
  });
  return proxy
}

Works for everything and doesn't need the final () at the end of the function like some other solutions.

适用于所有内容,并且不需要函数末尾的final(),就像其他解决方案一样。

console.log(add(1)(2)(3)(10));    // 16
console.log(add(10)(10));         // 20

#6


6  

ES6 syntax makes this nice and simple:

ES6语法使这很简单:

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

console.log(add(2, 5)); 
// output: 7

const add2 = a => b => a + b;

console.log(add2(2)(5));
// output: 7

#7


3  

in addition to what's already said, here's a solution with generic currying (based on http://github.com/sstephenson/prototype/blob/master/src/lang/function.js#L180)

除了已经说过的,这里是一个通用currying的解决方案(基于http://github.com/sstephenson/prototype/blob/master/src/lang/function.js#L180)

Function.prototype.curry = function() {
    if (!arguments.length) return this;
    var __method = this, args = [].slice.call(arguments, 0);
    return function() {
      return __method.apply(this, [].concat(
        [].slice.call(args, 0),
        [].slice.call(arguments, 0)));
   }
}


add = function(x) {
    return (function (x, y) { return x + y }).curry(x)
}

console.log(add(2)(3))

#8


3  

Concept of CLOSURES can be used in this case.
The function "add" returns another function. The function being returned can access the variable in the parent scope (in this case variable a).

在这种情况下可以使用CLOSURES的概念。函数“add”返回另一个函数。返回的函数可以访问父作用域中的变量(在本例中为变量a)。

function add(a){

    return function(b){
        console.log(a + b);
    }

}


add(2)(3);

Here is a link to understand closures http://www.w3schools.com/js/js_function_closures.asp

这是一个了解闭包的链接http://www.w3schools.com/js/js_function_closures.asp

#9


3  

It's about JS curring and a little strict with valueOf:

这是关于JS curring和有点严格的valueOf:

function add(n){
  var addNext = function(x) {
    return add(n + x);
  };

  addNext.valueOf = function() {
    return n;
  };

  return addNext;
}

console.log(add(1)(2)(3)==6);//true
console.log(add(1)(2)(3)(4)==10);//true

It works like a charm with an unlimited adding chain!!

它就像一个无限添加链的魅力!

#10


2  

This is a generalized solution which will solve add(2,3)(), add(2)(3)() or any combination like add(2,1,3)(1)(1)(2,3)(4)(4,1,1)(). Please note that few security checks are not done and it can be optimized further.

这是一个通用的解决方案,它将解决add(2,3)(),add(2)(3)()或任何组合,如add(2,1,3)(1)(1)(2,3)( 4)(4,1,1)()。请注意,很少进行安全检查,可以进一步优化。

function add() {
	var total = 0;

	function sum(){
		if( arguments.length ){
			var arr = Array.prototype.slice.call(arguments).sort();
			total = total + arrayAdder(arr);
			return sum;
		}
		else{
			return total;
		}
	}

	if(arguments.length) {
		var arr1 = Array.prototype.slice.call(arguments).sort();
		var mytotal = arrayAdder(arr1);
		return sum(mytotal);
	}else{
		return sum();
	}

	function arrayAdder(arr){
		var x = 0;
		for (var i = 0; i < arr.length; i++) {
			x = x + arr[i];
		};
		return x;
	}
}
add(2,3)(1)(1)(1,2,3)();

#11


1  

function add(a, b){
 return a && b ? a+b : function(c){return a+c;}
}

console.log(add(2, 3));
console.log(add(2)(3));

#12


1  

This will handle both

这将处理两者

add(2,3) // 5

or

add(2)(3) // 5

This is an ES6 curry example...

这是ES6咖喱的例子......

const add = (a, b) => (b || b === 0) ? a + b : (b) => a + b;

#13


1  

With ES6 spread ... operator and .reduce function. With that variant you will get chaining syntax but last call () is required here because function is always returned:

使用ES6传播...运算符和.reduce函数。使用该变体,您将获得链接语法,但此处需要最后一次调用(),因为始终返回函数:

function add(...args) {
    if (!args.length) return 0;
    const result = args.reduce((accumulator, value) => accumulator + value, 0);
    const sum = (...innerArgs) => {
        if (innerArgs.length === 0) return result;
        return add(...args, ...innerArgs);    
    };
    return sum;
}




// it's just for fiddle output
document.getElementById('output').innerHTML = `
<br><br>add() === 0: ${add() === 0 ? 'true' : 'false, res=' + add()}
<br><br>add(1)(2)() === 3: ${add(1)(2)() === 3 ? 'true' : 'false, res=' + add(1)(2)()}
<br><br>add(1,2)() === 3: ${add(1,2)() === 3 ? 'true' : 'false, res=' + add(1,2)()}
<br><br>add(1)(1,1)() === 3: ${add(1)(1,1)() === 3 ? 'true' : 'false, res=' + add(1)(1,1)()}
<br><br>add(2,3)(1)(1)(1,2,3)() === 13: ${add(2,3)(1)(1)(1,2,3)() === 13 ? 'true' : 'false, res=' + add(2,3)(1)(1)(1,2,3)()}
`;
<div id='output'></div>

#14


0  

function add() { var sum = 0;

function add(){var sum = 0;

    function add() {
        for (var i=0; i<arguments.length; i++) {
            sum += Number(arguments[i]);
        }
        return add;
    }
    add.valueOf = function valueOf(){
        return parseInt(sum);
    };
    return add.apply(null,arguments);
}

// ...

console.log(add() + 0);               // 0
console.log(add(1) + 0);/*                 // 1
console.log(add(1,2) + 0);               // 3

#15


0  

function A(a){
  return function B(b){
      return a+b;
  }
}

I found a nice explanation for this type of method. It is known as Syntax of Closures

我找到了这种方法的一个很好的解释。它被称为闭包语法

please refer this link Syntax of Closures

请参阅此链接语法闭包

#16


0  

const add = a => b => b ? add(a+b) : a;

console.log(add(1)(2)(3)());

Or (`${a} ${b}`) for strings.

或者(`$ {a} $ {b}`)表示字符串。

#17


-1  

function add () {
    var args = Array.prototype.slice.call(arguments);
 
    var fn = function () {
        var arg_fn = Array.prototype.slice.call(arguments);
        return add.apply(null, args.concat(arg_fn));
    }
 
    fn.valueOf = function () {
        return args.reduce(function(a, b) {
            return a + b;
        })
    }
 
    return fn;
}

console.log(add(1));
console.log(add(1)(2));
console.log(add(1)(2)(5));

from http://www.cnblogs.com/coco1s/p/6509141.html

相关文章