I saw such a topic recently

Please write a multiply function that satisfies multiply(x)(y)(z); , and output the result of the operation, as shown in the following example (note: the last parameter indicates the end); console.log(multiply(2)(3)(4)()); // output: 24 console.log(multiply(4)(3)()); // output: 12

This one feels the idea is simple, but the implementation will have a lot of details of the topic.

You can use closures to store the parameters of each step, and then return the parameters when they are empty.

You can also calculate each ride and return the value if the argument is empty.

Intuitively, I started to think that it would be possible to construct a composite function like (x) => NFN (x), but the coincidence function would become unexecutable after two executions. The root cause should be that the fn returned every time should be a function, and a value like NFN (x) can no longer be a function.

Answer 1:

function multiply(n) {
    const nums = []
    function _multiply(n) {
        if (n === undefined) {
            return nums.reduce((pre, value) = > {
                return pre * value
            })
        } else {
            nums.push(n)
        }
        return _multiply
    }
    return _multiply(n)
}
Copy the code

Answer 2:

function multiply(n) {
  return (function _multiply(. args) {
    return function(. args2) {
      if (args2.length === 0) {
        return args.reduce((prev, value) = > {
          return prev * value
        })
      }
      return_multiply(... args, ... args2) } })(n) }Copy the code

So, function Curry, but it’s a little different.

Curry is implemented by Lodash

var abc = function(a, b, c) {
  return [a, b, c];
};
 
var curried = _.curry(abc);
 
curried(1) (2) (3);
Copy the code

Lodash.com/docs/4.17.1…

If you have time to look at the LoDash source code, you will have a better understanding of the various concepts.

Another article introduces the function of curry article is: useful. Javascript. The info/currying – pa…

The answer is:

function curry(func) {
  return function curried(. args) {
    if (args.length >= func.length) {
      return func.apply(this, args);
    } else {
      return function(. args2) {
        return curried.apply(this, args.concat(args2)); }}}; }function sum(a, b, c) {
  return a + b + c;
}

let curriedSum = curry(sum);

alert( curriedSum(1.2.3));// 6, can still be called normally
alert( curriedSum(1) (2.3));// 6, currization of the first argument
alert( curriedSum(1) (2) (3));// 6, full cremation

Copy the code