Function Currying in JavaScript

Source:http://tech.pro/tutorial/2011/functional-javascript-part-4-function-currying

Currying is the process of transforming a function that takes multiple arguments into a function that takes just a single argument and returns another function if any arguments are still needed.

Function currying allows and encourages you to compartmentalize complex functionality into smaller and easier to reason about parts. These smaller units of logic are dramatically easier to understand and test, and then your application becomes a nice and clean composition of the smaller parts.

var sendMsg = function (from, to, msg) {
    alert(["Hello " + to + ",", msg, "Sincerely,", "- " + from].join("\n"));
};
var sendMsgCurried = curry(sendMsg); // returns function(a,b,c)
var sendMsgFromJohnToBob = sendMsgCurried("John")("Bob"); // returns function(c)
sendMsgFromJohnToBob("Come join the curry party!");
//=> "Hello Bob, Come join the curry party! Sincerely, - John"

If we know the number of arguments, we can do manual currying.

// uncurried
var example1 = function (a, b, c) {
    // do something with a, b, and c
};

// curried
var example2 = function(a) {
    return function (b) {
        return function (c) {
            // do something with a, b, and c
        };
    };
};

a simple helper function sub_curry

function sub_curry(fn /*, variable number of args */) {
    var args = [].slice.call(arguments, 1);
    return function () {
        return fn.apply(this, args.concat(toArray(arguments)));
    };
}

a complete curry function

function curry(fn, length) {
    // capture fn‘s # of parameters
    length = length || fn.length;
    return function () {
        if (arguments.length < length) {
            // not all arguments have been specified. Curry once more.
            var combined = [fn].concat(toArray(arguments));
            return length - arguments.length > 0
                ? curry(sub_curry.apply(this, combined), length - arguments.length)
                : sub_curry.call(this, combined );
        } else {
            // all arguments have been specified, actually call function
            return fn.apply(this, arguments);
        }
    };
}

CodeWars - A Chain adding function

We want to create a function that will add numbers together when called in succession.

add(1)(2);
// returns 3

We also want to be able to continue to add numbers to our chain.

add(1)(2)(3); // 6
add(1)(2)(3)(4); // 10
add(1)(2)(3)(4)(5); // 15

and so on.

A single call should return the number passed in.

add(1) // 1

and we should be able to store the result and reuse it.

var addTwo = add(2);
addTwo // 2
addTwo(3) // 5
addTwo(3)(5) // 10

We can assume any number being passed in will be valid javascript number.

function add(n){
    var f = function(x){
        return add(n+x)
    }
    f.toString = function(){
        return n
    }
    return f
}
时间: 2024-11-09 09:32:15

Function Currying in JavaScript的相关文章

[Javascript] What is JavaScript Function Currying?

Currying is a core concept of functional programming and a useful tool for any developer's toolbelt. Example 1: let f = a => b => c => a+b+c; let result = f(1)(2)(3); console.log(result); // 6 Example 2: <!DOCTYPE html> <html> <hea

javascript 中 function bind()

Function bind() and currying <%-- All JavaScript functions have a method called bind that binds to an object and returns a new function. The first argument to bind sets the this context of the function. function area (height) { return this.width * he

Javascript学习之函数(function)

在JS中,Function(函数)类型实际上是对象;每个函数都是Function类型的实例,而且都与其他引用类型一样具有属性和方法.由于函数是对象,因此函数名实际上也是一个指向函数对象的指针. 一 函数的声明方式 //1.函数声明方式 function add(num1,num2){ return num1+num2; } //2.函数表达式定义函数 var add= function(num1,num2){ // 通过变量box即可引用函数; return num1+num2; }; // 注

理清javascript中prototype、__proto__、Object、Function的关系,更好地理解原型继承

本文参考了http://www.blogjava.net/heavensay/archive/2013/10/20/405440.html这篇文章,对其内容作了个简单总结,形成了几条简单的结论,让读者更容易记住prototype.__proto__.Object.Function之间的关系. 结论1:Object.prototype只是一个普通对象,它是js原型链的最顶端. (typeof Object.prototype) === object;//true Object.prototype.

javascript中的立即执行函数(function(){…})()

javascript中的立即执行函数(function(){…})() 深入理解javascript中的立即执行函数,立即执行函数也叫立即调用函数,通常它的写法是用(function(){…})()包住业务代码,使用jquery时比较常见. ( function(){…} )()和( function (){…} () )是两种javascript立即执行函数的常见写法,最初我以为是一个括号包裹匿名函数,再在后面加个括号调用函数,最后达到函数定义后立即执行的目的,后来发现加括号的原因并非如此.要

JavaScript笔记之Function

一.函数定义 (1)使用function declaration 格式:function functionName(parameters) { function body } 注:此种方式声明的函数作用域是全局的,即在声明之前可以调用 (2)使用function expression 格式:var name = function (parameters) { function body }; 注:与(1)不同,在声明之前不可以调用 (3)使用function constructor() 格式:v

【JavaScript】JS_Object跟Function的区别

JS_Object和Function的区别 我们本次的解释,主要通过下图 粗看该图,估计你不一定能看明白.不过接下来让我逐行向你解释. 最左侧:意思是,有两个对象f1和f2,他们是通过new Foo()出来的. 中间:Foo()就是最左侧用到的Foo() 最右侧:表示,函数Foo()的prototype属性! 1.__proto__的虚线:该条线表示通过f1.__proto__可以访问到Foo.prototype,其实两者是等价的. 2.constructor实现:表示通过Foo.prototy

理解JavaScript的function

JavaScript中最有特色而又让你困惑的function算一个了,下面看一下常用操作: function doit(){ ..... } doit(); JavaScript中的函数我们可以把它当作方法使用兰西县璩家摄影 var obj=new Object(); obj.say=function(){ ..... } obj.say(); 而function实际上就是对象(即Function类型的实例) function result(num1, num2) { return num1 +

javascript (function(){})() 【转】

代码如下: (function(){ //这里忽略jQuery所有实现 })(); (function(){ //这里忽略jQuery所有实现 })(); 半年前初次接触jQuery的时候,我也像其他人一样很兴奋地想看看源码是什么样 的.然而,在看到源码的第一眼,我就迷糊了.为什么只有一个匿 名函数又没看到运行(当然是运行了……),就能有jQuery这么个函数库了?于是,我抱着疑问来到CSDN.结果相信现在很多人都很清楚了(因为在我之 后也不乏来者,呵呵~).当一个匿名函数被括起来,然后再在后面