JavaScript - Create a function that sums two arguments together


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:

  • var sumTwoAnd = addTogether(2);

  • sumTwoAnd(3) returns 5.

  • If either argument isn't a valid number, return undefined


Solution 1 Basic approach


function addTogether() {
    var index = [].slice.call(arguments)
    console.log(index)

    if (!index.every(items => {
        return typeof items === 'number';

    })) { return }
    if (index.length === 2) {
        return index[0] + index[1]
    }
    var firstIndex = index[0]
    //stores the fistindex and look for the second through recursion and store both the value
    var addOneMOre = function (secondIndex) {
        return addTogether(firstIndex, secondIndex)
    }
    return addOneMOre
}
console.log(addTogether(2, 3));
console.log(addTogether(2)(5));
console.log(addTogether(2)([3]));
console.log(addTogether(2, "3"));
console.log(addTogether("http://bit.ly/IqT6zt"));









Output:


5
7
undefined
undefined
undefined



Solution 2 jshint esversion: 6


function addTogether() {
    var args = Array.from(arguments);
    return args.some(n => typeof n !== "number")
        ? undefined
        : args.length > 1
            ? args.reduce((acc, n) => (acc += n), 0)
            : n => (typeof n === "number" ? n + args[0] : undefined);
}
console.log(addTogether(2, 3));

Output:


5