Function Currying in JavaScript

來源:互聯網
上載者:User

標籤:

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.

// uncurriedvar example1 = function (a, b, c) {    // do something with a, b, and c};// curriedvar 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); // 6add(1)(2)(3)(4); // 10add(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 // 2addTwo(3) // 5addTwo(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}

 

Function Currying in JavaScript

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.