Home >Web Front-end >JS Tutorial >Detailed explanation of function combination and currying in JavaScript (with examples)

Detailed explanation of function combination and currying in JavaScript (with examples)

不言
不言forward
2018-10-13 14:42:471939browse

This article brings you a detailed explanation of JavaScript function combination and currying (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

We all know the single responsibility principle. In fact, S (SRP, Single responsibility principle) in object-oriented SOLID. In functional programming, each function is a unit and should only do one thing. But the real world is always complex, and when mapping the real world to programming, a single function doesn't make much sense. At this time, function composition and currying are needed.

Chain call

If you have used jQuery, you all know what chain call is, such as $('.post').eq(1).attr('data- test', 'test').Some of the native string and array methods of javascript can also write chain call styles:

'Hello, world!'.split('').reverse().join('') // "!dlrow ,olleH"

First of all, chain calls are based on objects, the above one A method split, reverse, join cannot be played if it is separated from the previous object "Hello, world!".

In functional programming, methods are independent of data. We can write the above in a functional way:

const split = (tag, xs) => xs.split(tag)
const reverse = xs => xs.reverse()
const join = (tag, xs) => xs.join(tag)

join('',reverse(split('','Hello, world!'))) // "!dlrow ,olleH"

You will definitely say, you are kidding me. How is this better than chained calls? This still relies on data. Without passing `Hello, world!', your series of function combinations will not work. The only advantage here is that the individual methods can be reused. Don’t panic, there is so much content later and I will optimize it for you (foolishly). Before proceeding with the transformation, we first introduce two concepts, partial application and currying.

Partial application

Partial application is a process that processes function parameters. It receives some parameters and then returns a function that receives fewer parameters. This is part of the application. We use bind to implement it:

const addThreeArg = (x, y, z) => x + y + z;

const addTwoArg = addThreeNumber.bind(null, 1)
const addOneArg = addThreeNumber.bind(null, 1, 2)

addTwoArg(2, 3) // 6
addOneArg(7) // 10

The above uses bind to generate two other functions, which accept the remaining parameters respectively. This is part of the application. Of course you can do it in other ways.

Problems with some applications

The main problem with some applications is that the function type it returns cannot be directly inferred. As mentioned before, some applications return a function that accepts fewer parameters without specifying how many parameters are returned. This is something implicit, you need to look at the code. Only then do you know how many parameters the returned function receives.

Currying

Currying definition: You can call a function, but you don’t pass all the parameters to it at once. This function will return a function to receive the next one parameter.

const add = x => y => x + y
const plusOne = add(1)
plusOne(10) // 11

The curried function returns a function that receives only one parameter, and the returned function type is predictable.

Of course, in actual development, many functions are not curried. We can use some tool functions to convert:

const curry = (fn) => { // fn可以是任何参数的函数
  const arity = fn.length;

  return function $curry(...args) {
    if (args.length <p> You can also use the curry method provided in the open source library Ramda . </p><h3>Oh, currying. what's the function? </h3><p>For example</p><pre class="brush:php;toolbar:false">const currySplit = curry((tag, xs) => xs.split(tag))
const split = (tag, xs) => xs.split(tag)

// 我现在需要一个函数去split ","

const splitComma = currySplit(',') //by curry

const splitComma = string => split(',', string)

You can see that when the curried function generates a new function, it has nothing to do with the data. Comparing the two processes of generating new functions, the one without currying is relatively verbose.

Function combination

First give the code:

const compose = (...fns) => (...args) => fns.reduceRight((res, fn) => [fn.call(null, ...res)], args)[0];

In fact, compose does a total of two things:

  1. Receives a set of functions , returns a function, does not execute the function immediately

  2. Combined function, combines the functions passed to him from left to right.

Some students may not be very familiar with the reduceRight above. Let me give you an example of 2 yuan and 3 yuan:

const compose = (f, g) => (...args) => f(g(...args))
const compose3 = (f, g, z) => (...args) => f(g(z(...args)))

Function calls are from left to right, data The flow is also the same from left to right. Of course you can define right to left, but it's not that semantically meaningful.

Okay, now let’s optimize the initial example:

const split = curry((tag, xs) => xs.split(tag))
const reverse = xs => xs.reverse()
const join = curry((tag, xs) => xs.join(tag))

const reverseWords = compose(join(''), reverse, split(''))

reverseWords('Hello,world!');

Is it much simpler and easier to understand? The reverseWords here is also the Pointfree code style we talked about before. It does not rely on data or external state, it is a function combined together.

Pointfree I introduced the concept of JS functional programming in the previous article, and also explained its advantages and disadvantages. Interested friends can take a look.

Associative Law of Function Combination

Let’s first review the associative law of elementary school knowledge addition: a (b c)=(a b) c. I won’t explain it, you should be able to understand.

Looking back, function combinations actually have associative laws:

compose(f, compose(g, h)) === compose(compose(f, g), h);

This is a benefit for our programming. Our function combinations can be combined and cached at will:

const split = curry((tag, xs) => xs.split(tag))
const reverse = xs => xs.reverse()
const join = curry((tag, xs) => xs.join(tag))

const getReverseArray = compose(reverse, split(''))

const reverseWords = compose(join(''), getReverseArray)

reverseWords('Hello,world!');

Supplementary mind map:

Detailed explanation of function combination and currying in JavaScript (with examples)


The above is the detailed content of Detailed explanation of function combination and currying in JavaScript (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete