Variadic curried sum function

前端 未结 16 2011
清酒与你
清酒与你 2020-11-22 06:33

I need a js sum function to work like this:

sum(1)(2) = 3
sum(1)(2)(3) = 6
sum(1)(2)(3)(4) = 10 
etc.

I heard it can\'t be done. But heard

16条回答
  •  日久生厌
    2020-11-22 07:24

    Here's a solution with a generic variadic curry function in ES6 Javascript, with the caveat that a final () is needed to invoke the arguments:

    const curry = (f) =>
       (...args) => args.length? curry(f.bind(0, ...args)): f();
    
    const sum = (...values) => values.reduce((total, current) => total + current, 0)
    curry(sum)(2)(2)(1)() == 5 // true
    

    Here's another one that doesn't need (), using valueOf as in @rafael's answer. I feel like using valueOf in this way (or perhaps at all) is very confusing to people reading your code, but each to their own.

    The toString in that answer is unnecessary. Internally, when javascript performs a type coersion it always calls valueOf() before calling toString().

    
    // invokes a function if it is used as a value
    const autoInvoke = (f) => Object.assign(f, { valueOf: f } );
    
    const curry = autoInvoke((f) =>
       (...args) => args.length? autoInvoke(curry(f.bind(0, ...args))): f());
    
    
    const sum = (...values) => values.reduce((total, current) => total + current, 0)
    curry(sum)(2)(2)(1) + 0 == 5 // true
    

提交回复
热议问题