Home  >  Article  >  Web Front-end  >  Detailed explanation of examples of js currying

Detailed explanation of examples of js currying

零下一度
零下一度Original
2017-06-26 15:14:381490browse

1. Source

In computer science, currying is to transform a function that accepts multiple parameters into a function that accepts a single parameter (the first parameter of the original function), and A technique for returning a new function that accepts the remaining arguments and returns a result. This technique was named by Christopher Strachey after logician Haskell Curry, although it was invented by Moses Schnfinkel and Gottlob Frege.

2. curring(1)(2)(3)(4)() How to add parameters to get the result to be 10?

1. In fact, we only need to think about how to retain each parameter, and finally accumulate the parameters when calling? This is the focus of our thinking.

function keepParams(){var arg = [];return function params(){if(arguments.length === 0){return arg;
    }
    Array.prototype.push.apply(arg,arguments);  //对apply方法不熟悉的可以去百度下return params;
}
}var curring = keepParams();
console.log(curring(1)(2)(3)(4)()); // [1, 2, 3, 4]

2. Through the first step, we can get the parameters. Then we can do whatever we want to do next.

How to implement addition?

3. Change the basic function

function add(){var sum = 0,l = arguments.length;for(var i = 0; i < l; i++){
        sum += arguments[i];
    }return sum;
};function keepParams(fn){var arg = [];return function params(){if(arguments.length === 0){return fn.apply(this,arg);
        }
        Array.prototype.push.apply(arg,arguments);  //对apply方法不熟悉的可以去百度下return params;
    }
}var curring = keepParams(add);//console.log(curring(1)(2)(3)(4)()); // 10console.log(curring(1)(2,3,4)()); // 10

4. Now that the third step of addition is implemented, then multiply and divide. Wait for a series of operations to be completed. However, you need to pay attention to the use of closures. If you call the same method twice in a row.

arg will be saved in memory

console.log(curring(1)(2)(3)(4)()); // 10console.log(curring(1)(2,3,4)()); // 20

The above is the detailed content of Detailed explanation of examples of js currying. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn