DEV Community

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

Collapse
 
minimumviableperson profile image
Nicolas Marcora

Nice one! I agree this is a very weird interview question to be asking, but since we're already doing crazy stuff, you inspired me to go further. This version can accept multiple numbers or callbacks at once, and will add/apply all to the count.

const add = (...args) => {
    let count = 0

    const applyArguments = args => args.reduce((acc, arg) => {
        if (typeof arg === 'function') return arg(acc)
        if (typeof arg === 'number') return acc + arg
        return acc
    }, count)

    const adder = (...args) => args[0] === undefined
        ? count
        : (count = applyArguments(args), adder)

    adder.valueOf = () => count

    return adder(...args)
}


const double = n => n * 2

const timesTen = n => n * 10

add(1, 2, 3)(double)(10)(timesTen, double)(2)()
// 442

+add(1, 2, 3)(double)(10)(timesTen, double)(2)
// 442

add(10)(double) + add(20)(timesTen)
// 220
Collapse
 
karataev profile image
Eugene Karataev

Thanks for sharing, I like how you go deeper with add functionality.

That escalated quickly