Currying in Javascript

Currying in Javascript

Currying is a technique in functional programming where a function with multiple arguments is transformed into a sequence of functions, each taking a single argument. This improves composability and allows partial application of functions.


function add(x) {
    return function(y) {
        return x + y;
    };
}

const addTwo = add(2);
console.log(addTwo(3)); // Output: 5

2. sum(2)(6)(1)

This function demonstrates currying by taking three separate arguments and adding them together in a sequence using nested functions.


function sum(x) {
    return function(y) {
        return function(z) {
            return x + y + z;
        };
    };
}

console.log(sum(2)(6)(1)); // Output: 9

4. Write a currying function evaluate("sum")(4)(2)

This question showcases a curried function evaluate that takes an operation string and two numbers, then performs the corresponding operation (sum, multiply, divide, subtract) based on the string input.


function evaluate(operation) {
    return function(x) {
        return function(y) {
            switch (operation) {
                case 'sum':
                    return x + y;
                case 'multiply':
                    return x * y;
                case 'divide':
                    return x / y;
                case 'subtract':
                    return x - y;
                default:
                    return NaN;
            }
        };
    };
}

console.log(evaluate('sum')(4)(2)); // Output: 6

5. Infinite Currying -> sum(1)(2)(3)....(n)

This example illustrates how currying can be used recursively to handle an indefinite number of arguments, continually adding them together until a termination condition is met.


function sumNumbers(x) {
    let sum = x;

    function inner(y) {
        sum += y;
        return inner;
    }

    inner.toString = function() {
        return sum;
    };

    return inner;
}

console.log(sumNumbers(1)(2)(3)); // Output: 6
console.log(sumNumbers(1)(2)(3)(4)(5)); // Output: 15

6. Currying vs Partial Application

This question compares currying and partial application, showing how currying allows for creating reusable functions with specific arguments filled in, while partial application involves pre-filling some arguments and leaving others for later.

Currying Example:


function multiply(a) {
    return function(b) {
        return a * b;
    };
}

const multiplyByTwo = multiply(2);
console.log(multiplyByTwo(5)); // Output: 10

Partial Application Example:


function greet(greeting, name) {
    return greeting + ', ' + name + '!';
}

const greetHello = greet.bind(null, 'Hello');
console.log(greetHello('John')); // Output: Hello, John!

7. Real-world example of currying => Manipulating DOM

In this example, currying is used to create a function that updates the text content of an HTML element identified by its ID. This showcases a practical application of currying in web development for DOM manipulation.


function updateElementContentById(id) {
    return function(content) {
        const element = document.getElementById(id);
        if (element) {
            element.textContent = content;
        } else {
            console.error('Element with id ' + id + ' not found.');
        }
    };
}

// Usage
const updateTitle = updateElementContentById('title');
updateTitle('New Title');

8. Curry() implementation

This code snippet demonstrates a custom implementation of the curry function, which transforms a multi-argument function into a curried function, enabling partial application and composability. It's applied to a simple sum function for demonstration.

// Custom curry function implementation
function curry(func) {
    return function curried(...args) {
        if (args.length >= func.length) {
            return func.apply(this, args);
        } else {
            return function(...moreArgs) {
                return curried.apply(this, args.concat(moreArgs));
            };
        }
    };
}

// Example usage
function simpleSum(a, b, c) {
    return a + b + c;
}

const curriedSum = curry(simpleSum);
console.log(curriedSum(1)(2)(3)); // Output: 6
console.log(curriedSum(1, 2)(3)); // Output: 6
console.log(curriedSum(1)(2, 3)); // Output: 6
console.log(curriedSum(1, 2, 3)); // Output: 6