Skip to content

Currying Demo #146

@hoperyy

Description

@hoperyy
const curry = (fn, ...args) => {
    const initAllArgs = () => [...args];
    let allArgs = initAllArgs();

    const innerFn = function(...args) {
        if (args.length == 0) {
            const result = fn.apply(this, allArgs);
            allArgs = initAllArgs();
            return result;
        } else {
            allArgs.push(...args);
            return innerFn;
        }
    };

    return innerFn;
};

const add = (...args) => args.reduce((pre, cur) => pre + cur);

const newAdd = curry(add, 5, 6);

console.log(newAdd(1)(2)(3, 4)());
console.log(newAdd(1, 2)(3, 4)());
console.log(newAdd(1, 2, 3, 4)());

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions