loading...

Discussion on: Interview Question Journey - Currying, Closures, Type Coercion, oh my 😱

Collapse
dance2die profile image
Sung M. Kim

Thanks for the fun post Eugene.

After reading your post,
I was playing around to implement it with Function#bind but it seems like it's not possible to know when user is "done" with arguments and calculate the "add" without knowing the "arity" (parameter count).

I ended up using "done" as an end condition but one can probably specify the arity initially as a second argument of curriedAdd(arity, value) and compare the arity against the argument length.

using bind

But then at this point, it will be a partial application, not a currying...

And then I was surprised 😮 to learn from your post that the type-coercion using + causes .valueOf to be called.

coercion.

So I've tried for the 3rd time to make the function work as yours do using .valueOf.

3rd try

This post got me really thinking about currying and steps to reach your conclusion as well as mine.

Below is the source above.

function curriedAdd(v1) {
    if (arguments[arguments.length - 1] === "done") {
        console.log(`done...`)
        return Array.prototype.slice
            .apply(arguments, [0, arguments.length - 1])
            .reduce((acc, v) => acc+=v)
    };
    console.log(`v1`, v1, `arguments`, ...arguments, 'arg.length', arguments.length)
    return curriedAdd.bind(null, ...arguments);
}

function curriedAdd2(arity, v1) {
    // "-1" to account for the arity
    if (arguments.length - 1 === arity) {
        return Array.prototype.slice
            .call(arguments, 1)
            .reduce((acc, v) => acc += v, 0)
    };
    return curriedAdd2.bind(null, ...arguments);
}


function curriedAdd3() {
    const inner = curriedAdd3.bind(null, ...arguments)
    inner.valueOf = () => [...arguments].reduce((acc, v) => acc += v, 0);
    return inner;
}

Collapse
karataev profile image
Eugene Karataev Author

Wow, thanks for the such detailed comment! I did not think about binding and collecting arguments with each function call. JS is so flexible language that allows many ways to solve a problem. Thanks for sharing your path!

Collapse
dance2die profile image
Sung M. Kim

I found your approach your readable as it is more intentional what the code is doing 🙂