freeCodeCamp.org


    Arguments Optional

    Create a function that sums two arguments together. If only one argument is provided, then return a function that expects one argument and returns the sum.

    For example, addTogether(2, 3) should return 5, and addTogether(2) should return a function.

    Calling this returned function with a single argument will then return the sum:

    1. var sumTwoAnd = addTogether(2);

    sumTwoAnd(3) returns 5.

    If either argument isn’t a valid number, return undefined.

    addTogether(2, 3) should return 5.

    Passed

    addTogether(23, 30) should return 53.

    Passed

    addTogether(5)(7) should return 12.

    Passed

    addTogether("http://bit.ly/IqT6zt") should return undefined.

    Passed

    addTogether(2, "3") should return undefined.

    Passed

    addTogether(2)([3]) should return undefined.

    freeCodeCamp Challenge Guide: Arguments Optional

    1. function addTogether() {
    2. let args = Array.prototype.slice.call(arguments, 0)
    3. let a = args[0]
    4. if (typeof a !== "number") return;
    5. if (arguments.length === 1) {
    6. return function () {
    7. let b = Array.prototype.slice.call(arguments, 0)[0]
    8. if (typeof b !== "number") return;
    9. return +a + + b
    10. }
    11. }
    12. let b = args[1]
    13. if (typeof b !== "number") return;
    14. return Array.prototype.reduce.call(arguments, (x, y) => +x + +y)
    15. }
    16. console.log(
    17. addTogether(2)(3)
    18. )