Skip to content

Instantly share code, notes, and snippets.

@mmloveaa
Last active January 4, 2016 23:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmloveaa/ca707b6514ec0fc03252 to your computer and use it in GitHub Desktop.
Save mmloveaa/ca707b6514ec0fc03252 to your computer and use it in GitHub Desktop.
Sum of numerous arguments
// 1/4/2016
// Sum of numerous arguments
// After calling the function findSum() with any number of non-negative integer
// arguments, it should return the sum of all those arguments. If no arguments
// are given, the function should return 0, if negative arguments are given, it
// should return -1.
// eg
// findSum(1,2,3,4); // returns 10
// findSum(1,-2); // returns -1
// findSum(); // returns 0
// Hint: research the arguments object on google or read Chapter 4 from
// Eloquent Javascript
// Test.assertEquals(findSum(1,3,5), 9, "1 + 3 + 5 = 9")
// Test.assertEquals(findSum(0,3,9,2), 14, "0+3+9+2 = 14")
// Test.assertEquals(findSum(), 0, "If no arguments, function should return 0")
// Test.assertEquals(findSum(1,-2,4) , -1, "If negative arguments are passed,
// function should return -1")
// Test.assertEquals(findSum(0), 0, "The sum of 0 is 0")
function findSum(){
var total = 0;
var arr1=Array.prototype.slice.call(arguments)
if (arr1.length===0){
return 0;
}
for(var i=0; i<arr1.length; i++){
if(arr1[i]<0){
return -1
}
if(typeof(arr1[i])==="number"){
total+=arr1[i]
}
else{
return false;
}
}
return total;
}
findSum(1,-2,4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment