The concept of currying a function, I’m sure many of you are familiar with it, but when do you actually use it?

What are the effects?

  1. Parameters of reuse
  2. Delay the
  3. Dynamically create

What usage scenarios?

Let’s illustrate the scenario for its three uses.

Scenario 1: Parameter reuse

Requirements: Several complete addresses need to be pieced according to the parameters, for example, juejin.cn/post/697868…

    // Regular implementation
    function spliceUrl(protocol, hostname, patchname) {
        return `${protocol}${hostname}${patchname}`;
    }
    const url1 = spliceUrl('https://'.'juejin.cn'.'/post/6978685539985653767/');
    const url2 = spliceUrl('https://'.'juejin.cn'.'/post/6989751020255445005');
Copy the code

As we can see from the above code, the parameters protocol and hostname are passed on each call.

    / / currying writing
    function spliceUrl(protocol, hostname) {
        return function(patchname) {
            return `${protocol}${hostname}${patchname}`; }}const urlBase = spliceUrl('https://'.'juejin.cn');
    const url1 = urlBase('/post/6978685539985653767/')
    const url2 = urlBase('/post/6989751020255445005');
Copy the code

Scenario 2: Delayed execution

Requirement: When implementing a summation function, you want to pass in parameters that satisfy sum(1)(2)(3)(4);

function currying(func) { 
  const args = [];
  return function result(. rest) { 
    if (rest.length === 0)
      returnfunc(... args); args.push(... rest);returnresult; }}const add = (. args) = > args.reduce((a, b) = > a + b); 
  const sum = currying(add);

console.log(sum(1) (2) (3) (4) ());/ / 10
Copy the code

Scenario 3: Dynamic creation

Requirement: Determine browser compatibility when listening for events

const whichEvent = (function() {
    if (document.addEventListener) {
        return function(element, event, handler) {
            if (element && event && handler) {
                element.addEventListener(event, handler, false); }}; }else {
        return function(element, event, handler) {
            if (element && event && handler) {
                element.attachEvent('on'+ event, handler); }}; }}) ();Copy the code

The advantage of this implementation is that it is actually determined in advance which method will be taken, so as to avoid having to judge every time.