Home > Web Front-end > JS Tutorial > body text

Ideas and source code for implementing curry function in JavaScript

不言
Release: 2018-11-20 15:22:45
forward
2148 people have browsed it

This article brings you the ideas and source code for implementing curry functions in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Implementation effect

const curry_fn = curry(fn);
fn(1, 2, 3) == curry_fn(1)(2)(3);
Copy after login

Implementation idea

  1. Storage incoming parameters through closure

  2. Obtain the number of parameters through the length attribute of the function

  3. When the number of parameters is not enough, the method directly returns the number of parameters stored

  4. Execute the original function when the number of parameters is equal to the original function

  • If you use the ES6 parameter default value, length will not be equal to the actual number of parameters

  • Parameters are obtained from arguments, and ES6 directly uses rest parameters to implement

Source code implementation

function curry(fn) {
    var length = fn.length; //获取原函数的参数个数
    var args = []; // args存储传入参数
    return function curryFn() {
        // 将arguments转换成数组
        var curryArgs = Array.prototype.slice.call(arguments); 
        args = args.concat(curryArgs);
        if (args.length > length) {
            throw new Error('arguments length error')
        }
        // 存储的参数个数等于原函数参数个数时执行原函数
        if (args.length === length) {
            return fn.apply(null, args);
        }
        // 否则继续返回函数
        return curryFn;
    };
}
Copy after login

ES6 version

function curry(fn) {
    let length = fn.length;
    let args = [];
    return function curryFn(...curryArgs) {
        args = args.concat(curryArgs);
        if (args.length > length) {
            throw new Error('arguments length error')
        }
        if (args.length === length) {
            return fn(...args);
        }
        return curryFn;
    }
}
Copy after login

The above is the detailed content of Ideas and source code for implementing curry function in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!