search
HomeWeb Front-endJS TutorialHow to implement the exquisite automatic currying function in JS

How to implement the exquisite automatic currying function in JS

Dec 13, 2017 am 09:27 AM
javascriptFunctionautomatic

This article gives you a detailed analysis of the exquisite automatic currying method in JS and analyzes the process and principles through code examples. Please refer to it and study it. I hope it can help you.

What is currying?

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 returns the remaining parameters. The technique of a new function that takes 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.

The theory seems overwhelming? It doesn’t matter, let’s take a look at the code first:

Curriization application

Suppose we need to implement a function that performs some processing on list elements, for example, let each element in the list add One, then it’s easy to think of:

const list = [0, 1, 2, 3];
list.map(elem => elem + 1);

It’s very simple, right? What if we want to add 2 more?

const list = [0, 1, 2, 3];
list.map(elem => elem + 1);
list.map(elem => elem + 2);

It seems that the efficiency is a bit low. Can the processing function be encapsulated?

But the callback function of map only accepts the current element elem as a parameter. It seems that there is no way to encapsulate it...

You may think: If you can get a partial configuration A good function is fine, for example:

// plus返回部分配置好的函数
const plus1 = plus(1);
const plus2 = plus(2);
plus1(5); // => 6
plus2(7); // => 9

Pass such a function into the map:

const list = [0, 1, 2, 3];
list.map(plus1); // => [1, 2, 3, 4]
list.map(plus2); // => [2, 3, 4, 5]

Isn’t it great? In this way, no matter how much you add, you only need list.map(plus(x)), which perfectly implements encapsulation and greatly improves readability!

But here comes the question: How to implement such a plus function?

This is where currying comes in handy:

currying function

// 原始的加法函数
function origPlus(a, b) {
 return a + b;
}
// 柯里化后的plus函数
function plus(a) {
 return function(b) {
  return a + b;
 }
}
// ES6写法
const plus = a => b => a + b;

You can see , the curried plus function first accepts a parameter a, and then returns a function that accepts a parameter b. Due to closure, the returned function can access the parameter a of the parent function, so for example: const plus2 = plus (2) can be equivalent to function plus2(b) { return 2 + b; }, thus achieving partial configuration.

In layman's terms, currying is a process of partially configuring a multi-parameter function, with each step returning a partially configured function that accepts a single parameter. In some extreme cases, you may need to partially configure a function many times, such as multiple additions:

multiPlus(1)(2)(3); // => 6

This way of writing seems strange, right? But if you fall into the big pit of functional programming in JS, this will be the norm.


Exquisite implementation of automatic currying in JS

Currying is a very important part of functional programming. Many functional languages ​​(eg. Haskell) automatically curry functions by default. However, JS does not do this, so we need to implement the automatic currying function ourselves.

First enter the code:

// ES5
function curry(fn) {
 function _c(restNum, argsList) {
  return restNum === 0 ?
   fn.apply(null, argsList) :
   function(x) {
    return _c(restNum - 1, argsList.concat(x));
   };
 }
 return _c(fn.length, []);
}
// ES6
const curry = fn => {
 const _c = (restNum, argsList) => restNum === 0 ?
  fn(...argsList) : x => _c(restNum - 1, [...argsList, x]);
 return _c(fn.length, []);
}
/***************** 使用 *********************/
var plus = curry(function(a, b) {
 return a + b;
});
// ES6
const plus = curry((a, b) => a + b);
plus(2)(4); // => 6

This achieves automatic currying!

If you can understand what happened, then congratulations! The boss everyone calls you is you! , please leave a like and start your functional career (funny

If you don’t understand what’s going on, don’t worry, I will help you sort out your ideas now.

Requirements Analysis

We need a curry function, which accepts a function to be curried as a parameter, returns a function for receiving a parameter, and puts the received parameters into a list. When the parameter When the number is sufficient, the original function is executed and the result is returned.

Implementation method

Simply thinking, we can know that the number of steps of the curried partial configuration function is equal to the number of parameters of fn. That is to say, the plus function with two parameters needs to be partially configured in two steps. The number of parameters of the function can be obtained through fn.length

The general idea is to put the parameter in every time a parameter is passed. In a parameter list argsList, if there are no parameters to be passed, then fn.apply(null, argsList) is called to execute the original function. To achieve this, we need an internal judgment function _c(restNum, argsList). ), the function accepts two parameters, one is the number of remaining parameters restNum, and the other is the list of obtained parameters argsList; the function of _c is to determine whether there are any parameters that have not been passed in. When restNum is zero, it is time to pass fn.apply(null, argsList) executes the original function and returns the result. If there are still parameters that need to be passed, that is, when restNum is not zero, a single-parameter function needs to be returned.

function(x) {
 return _c(restNum - 1, argsList.concat(x));
}

to continue receiving parameters. A tail recursion is formed here. After the function accepts a parameter, the number of remaining parameters restNum is reduced by one, and the new parameter x is added to argsList and passed to _c for recursion. Call. The result is that when the number of parameters is insufficient, the single-parameter function responsible for receiving new parameters is returned. When there are enough parameters, the original function is called and returned:

function curry(fn) {
 function _c(restNum, argsList) {
  return restNum === 0 ?
   fn.apply(null, argsList) :
   function(x) {
    return _c(restNum - 1, argsList.concat(x));
   };
 }
 return _c(fn.length, []); // 递归开始
}

Is it starting to become clearer?

The ES6 writing method looks much simpler due to the use of syntactic sugar such as array destructuring and arrow functions, but the idea is the same. Same~

// ES6
const curry = fn => {
 const _c = (restNum, argsList) => restNum === 0 ?
  fn(...argsList) : x => _c(restNum - 1, [...argsList, x]);

 return _c(fn.length, []);
}

Comparison with other methods


There is another commonly used method:

function curry(fn) {
 const len = fn.length;
 return function judge(...args1) {
  return args1.length >= len ?
  fn(...args1):
  function(...args2) {
   return judge(...[...args1, ...args2]);
  }
 }
}
// 使用箭头函数
const curry = fn => {
 const len = fn.length;
 const judge = (...args1) => args1.length >= len ?
  fn(...args1) : (...args2) => judge(...[...args1, ...args2]);
 return judge;
}

Compared with the method mentioned previously in this article, it is found that this method has two problems:

Relies on ES6 destructuring (the function parameter ...args1 and ...args2);

性能稍差一点。

性能问题

做个测试:

console.time("curry");
const plus = curry((a, b, c, d, e) => a + b + c + d + e);
plus(1)(2)(3)(4)(5);
console.timeEnd("curry");

在我的电脑(Manjaro Linux,Intel Xeon E5 2665,32GB DDR3 四通道1333Mhz,Node.js 9.2.0)上:

本篇提到的方法耗时约 0.325ms

其他方法的耗时约 0.345ms

差的这一点猜测是闭包的原因。由于闭包的访问比较耗性能,而这种方式形成了两个闭包:fn 和 len,前面提到的方法只形成了 fn 一个闭包,所以造成了这一微小的差距。

相关推荐:

详解JavaScript函数柯里化

js柯里化的实例详解

javascript中有趣的反柯里化深入分析_基础知识

The above is the detailed content of How to implement the exquisite automatic currying function in JS. 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
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

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

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools