DEV Community

Discussion on: Daily Challenge #123 - Curry me Softly

Collapse
 
aminnairi profile image
Amin

TypeScript

"use strict";

function curry<ParameterType, ReturnType>(callable: Function, ...initial: ParameterType[]): Function {
    return function(...additional: ParameterType[]): Function | ReturnType {
        const parameters: ParameterType[] = [...initial, ...additional];

        if (parameters.length >= callable.length) {
            return callable(...parameters);
        }

        return curry(callable, ...parameters);
    };
}

function add(x: number, y: number): number {
    return x + y;
}

const $add = curry<number, number>(add);
const $pow = curry<number, number>(Math.pow);

console.log($add(1, 2));    // 3
console.log($add(1));       // [Function]
console.log($add(1)(2));    // 3

console.log(Math.pow(10, 2));   // 100
console.log($pow(10));          // [Function]
console.log($pow(10, 2));       // 100

Playground

Repl.it.

Collapse
 
vonheikemen profile image
Heiker • Edited

I don't think this one is going to work with the last adder function, the one that uses reduce.

Collapse
 
aminnairi profile image
Amin • Edited

Yes indeed you are correct. My proposal is based on finite arguments. This means that it won't work for an infinite arguments as well as functions that relies on the arguments keyword.