Created
June 30, 2015 08:03
-
-
Save niksumeiko/d29d00f0e153ebdbf49b to your computer and use it in GitHub Desktop.
Sums up function arguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Sums up all given arguments. | |
* @param {...*} var_args Numbers or numbers alike to sum up. | |
* Numbers will be added as is, numbers in strings (e.g. '123.45') | |
* will be converted to numbers and added. NaNs are skipped. | |
* @return {number} The sum of number arguments. | |
*/ | |
function sum(var_args) { | |
var args = [].slice.call(arguments); | |
// If all arguments are numbers, it is not required to map | |
// converting every arguments to a number in arguments array. | |
return args.map(function(numberAlike) { | |
return typeof numberAlike === 'number' ? | |
numberAlike : (parseFloat(numberAlike, 10) || 0); | |
}).reduce(function(a, b) { | |
return a + b; | |
}, 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment