Table of Contents
Chain call
Partial application
Problems with some applications
Currying
Oh, currying. what's the function?
Function combination
Associative Law of Function Combination
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)

Oct 13, 2018 pm 02:42 PM
javascript node.js functional 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"
Copy after login

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"
Copy after login

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
Copy after login

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
Copy after login

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)
Copy after login

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];
Copy after login

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)))
Copy after login

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!');
Copy after login

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);
Copy after login

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!');
Copy after login

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 of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Python Lambda expressions: abbreviated, concise, powerful Python Lambda expressions: abbreviated, concise, powerful Feb 19, 2024 pm 08:10 PM

pythonLambda expressions are a powerful and flexible tool for creating concise, readable, and easy-to-use code. They are great for quickly creating anonymous functions that can be passed as arguments to other functions or stored in variables. The basic syntax of a Lambda expression is as follows: lambdaarguments:expression For example, the following Lambda expression adds two numbers: lambdax,y:x+y This Lambda expression can be passed to another function as an argument as follows: defsum( x,y):returnx+yresult=sum(lambdax,y:x+y,1,2)In this example

The AI ​​era of JS is here! The AI ​​era of JS is here! Apr 08, 2024 am 09:10 AM

Introduction to JS-Torch JS-Torch is a deep learning JavaScript library whose syntax is very similar to PyTorch. It contains a fully functional tensor object (can be used with tracked gradients), deep learning layers and functions, and an automatic differentiation engine. JS-Torch is suitable for deep learning research in JavaScript and provides many convenient tools and functions to accelerate deep learning development. Image PyTorch is an open source deep learning framework developed and maintained by Meta's research team. It provides a rich set of tools and libraries for building and training neural network models. PyTorch is designed to be simple, flexible and easy to use, and its dynamic computation graph features make

What are the advantages and disadvantages of Java functions compared to other functional programming languages? What are the advantages and disadvantages of Java functions compared to other functional programming languages? Apr 24, 2024 pm 02:51 PM

Java functional programming advantages include simplicity, composability, concurrency, test-friendliness, and performance. Disadvantages include learning curve, difficulty in debugging, limited flexibility, and performance overhead. Its key features include pure functions without side effects, data processing pipelines, stateless code, and efficient streaming APIs.

What are the benefits of using C++ lambda expressions for functional programming? What are the benefits of using C++ lambda expressions for functional programming? Apr 17, 2024 am 10:18 AM

C++ lambda expressions bring advantages to functional programming, including: Simplicity: Anonymous inline functions improve code readability. Code reuse: Lambda expressions can be passed or stored to facilitate code reuse. Encapsulation: Provides a way to encapsulate a piece of code without creating a separate function. Practical case: filtering odd numbers in the list. Calculate the sum of elements in a list. Lambda expressions achieve the simplicity, reusability, and encapsulation of functional programming.

Common mistakes and pitfalls of golang functional programming Common mistakes and pitfalls of golang functional programming Apr 30, 2024 pm 12:36 PM

There are five common mistakes and pitfalls to be aware of when using functional programming in Go: Avoid accidental modification of references and ensure that newly created variables are returned. To resolve concurrency issues, use synchronization mechanisms or avoid capturing external mutable state. Use partial functionalization sparingly to improve code readability and maintainability. Always handle errors in functions to ensure the robustness of your application. Consider the performance impact and optimize your code using inline functions, flattened data structures, and batching of operations.

Comparison of Golang and Node.js in backend development Comparison of Golang and Node.js in backend development Jun 03, 2024 pm 02:31 PM

Go and Node.js have differences in typing (strong/weak), concurrency (goroutine/event loop), and garbage collection (automatic/manual). Go has high throughput and low latency, and is suitable for high-load backends; Node.js is good at asynchronous I/O and is suitable for high concurrency and short requests. Practical cases of the two include Kubernetes (Go), database connection (Node.js), and web applications (Go/Node.js). The final choice depends on application needs, team skills, and personal preference.

Python Lambda expressions: Uncovering the power of anonymous functions Python Lambda expressions: Uncovering the power of anonymous functions Feb 24, 2024 am 09:01 AM

Lambda expression in python is another syntax form of anonymous function. It is a small anonymous function that can be defined anywhere in the program. A lambda expression consists of a parameter list and an expression, which can be any valid Python expression. The syntax of a Lambda expression is as follows: lambdaargument_list:expression. For example, the following Lambda expression returns the sum of two numbers: lambdax,y:x+y. This Lambda expression can be passed to other functions, such as the map() function: numbers=[ 1,2,3,4,5]result=map(lambda

See all articles