Skip to content

Instantly share code, notes, and snippets.

@dallas dallas/sum.js
Created May 13, 2010

Embed
What would you like to do?
creating sum functions as an exercise
// Sums all "number" arguments given. This includes floats by default.
//
// sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); //=> 55
// sum(1, "hey", 2, "3", 4, "five", 6, 'hi!', 7, 8.2, 9, 10); //=> 47.2
function sum() {
var sum = 0;
for (i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (typeof arg === 'number') sum += arg;
}
return sum;
}
# Sums all Numeric arguments given. Could be made to sum only Integer arguments.
# (would exclude 8.2 in the second example).
#
# sum 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 #=> 55
# sum 1, "hey", 2, "3", 4, "five", 6, 'hi!', 7, 8.2, 9, 10 #=> 47.2
def sum(*args)
args.inject 0 do |sum, a|
sum += (a.is_a?(Numeric) ? a : 0)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.