Javascript – Curry Functions

Wikipedia has the following to say about currying:

In mathematics and computer science, currying is the technique of translating the evaluation of a function that takes multiple arguments (or a tuple of arguments) into evaluating a sequence of functions, each with a single argument. Currying is related to, but not the same as, partial application.

https://en.wikipedia.org/wiki/Currying

Instead of putting multiple arguments in one function, I call a function multiple times, passing in one argument each time.  I have done three different versions using normal formatting, and fat arrows.

// Basic Curry example
function curryName(name) {
    return function(descrip) {
        return function(location) {
            return name + " is a " + descrip + " from " + location;
        };
    };
};

// With arrow functions
function curryName(name) {
    return descrip => {
        return location => {
            return name + " is a " + descrip + " from " + location;
        }
    }
};

// Function expression
const curryName =
    name =>
    descrip =>
    location =>
    name + " is a " + descrip + " from " + location;

const output = curryName("Brian")("Web developer")("San Diego");
console.log(output); // Brian is a Web developer from San Diego

 

Leave a Reply