Tag: curry

JavaScript Partials

In a previous post I introduced the curry function. To recap, currying creates a new function with the first n arguments pre-assigned:-

var subtract = function(a,b) {
    return a - b;

var subtractFrom8 = subtract.curry(8);

subtractFrom8(2); //6

Currying is an expressive and compact alternative to manually wrapping anonymous functions. I use it a lot. But sometimes its not enough – the problem is you can only pre-assign the first n arguments. What if we wanted to make a function and pre-assign the rightmost argument, or maybe the middle two? Enter partial:-

var subtract5 = subtract.partial(___,5);

subtract5(13); //8;

Continue reading “JavaScript Partials”

express yourself: rapid function definition

The native JavaScript function indexOf, applied to a String, returns the index of the first occurrence of a specified value. Useful as it is, I often find myself wishing for a variant method that will return the index after the occurrence so that I can pass the result to a slice call and return everything after a given character.

With this in mind, I created a method called express (as in expression, and alsoquick) which returns a new function by applying the expression argument to the result of the old function. Its partly inspired by the Haskell language and by Oliver Steele’s lambda function.

String.prototype.indexAfter = String.prototype.indexOf.express('r + 1');

Continue reading express yourself: rapid function definition”

Curry: cooking up tastier functions

Currying allows you to easily create custom functions by partially invoking an existing function. Here’s a simple example:

var add = function(a,b) {
    return a + b;

var addTen = add.curry(10); //create function that returns 10 + argument
addTen(20); //30

Generally, curry returns a copy of the invoking function, with its first n arguments pre-assigned with the arguments passed by the curry invocation.

Continue reading “Curry: cooking up tastier functions”