Skip to content

Instantly share code, notes, and snippets.

@niksumeiko
Created June 30, 2015 08:03
Show Gist options
  • Save niksumeiko/d29d00f0e153ebdbf49b to your computer and use it in GitHub Desktop.
Save niksumeiko/d29d00f0e153ebdbf49b to your computer and use it in GitHub Desktop.
Sums up function arguments
/**
* 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