search
HomeWeb Front-endJS TutorialDetailed explanation of function combination and currying in JavaScript (with examples)

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

Oct 13, 2018 pm 02:42 PM
javascriptnode.jsfunctional programming

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 id="Oh-currying-what-s-the-function">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思否. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),