Skip to content

Instantly share code, notes, and snippets.

@joeegan
Created September 30, 2012 22:19
Show Gist options
  • Save joeegan/3808603 to your computer and use it in GitHub Desktop.
Save joeegan/3808603 to your computer and use it in GitHub Desktop.
javascript recursive sum and max
function sumNonRecursive(arr) {
var n = 0;
for (var i = 0; i < arr.length; i++) {
n = n + arr[i];
}
return n;
}
var numArray = [5,2,3];
console.log(sumNonRecursive(numArray));
//////////
Array.prototype.head = function(){
return this[0];
};
Array.prototype.last = function(){
if (this.length == 0) {
return this;
}
else {
return this[this.length -1];
}
};
Array.prototype.tail = function(){
var t = this.splice(0,1);
return this;
};
function sum(arr) {
if (arr.length == 0) {
return 0;
}
else {
return arr.head() + sum(arr.tail()); // This line is returned last (arr.head + 0)
}
}
var test = sum([1,2,3,6]);
console.log(test);
///////////
function max(arr) {
if (arr.length == 1) {
return arr[0];
}
var f = arr.head();
var l = arr.last();
return max(f < l ? arr.slice(1) : arr.slice(0, -1));
}
var numbers = [44,46,41,-2,-200,99,124];
console.log(max(numbers));
@msafi
Copy link

msafi commented Jul 11, 2015

Thanks. This helped me understand recursion in JS! :)

@milesmgit
Copy link

good stuff thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment