Skip to content

Instantly share code, notes, and snippets.

@fakefarm
Created August 14, 2014 11:57
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 fakefarm/22e704e7ee03e994f228 to your computer and use it in GitHub Desktop.
Save fakefarm/22e704e7ee03e994f228 to your computer and use it in GitHub Desktop.
have some fun
function sum ( args ) {
var array, sum = 0; // Set vars
// Conditional to type check what the arguments are
if ( typeof args == 'number' ) { // If not an array, then convert it to one.
array = Array.prototype.slice.call(arguments, 0); // Gotcha, using the key word 'arguments', not the 'args' word. 'arguments' is a special word in javascript that looks like an array, but is not.
} else {
array = args;
}
for ( i in array ) { // I assume recursion could be used here if I knew how recursion worked.
sum += array[i];
}
return sum; // Must explicity use return or you will get back undefined.
};
@fakefarm
Copy link
Author

// chat w/ @dhassler

function recur_sum(nums) {
    if (nums.length == 0) { return 0;}
        else if (nums.length == 1) { return nums[0]; }
    else { return nums[0] + recur_sum(nums[1..nums.length]) } 
}

function nth(nums, pos) {
  if (pos > 1) { nth(nums[1..-1], pos--) }
  else { return nums[0]; }
}

nth([10,20,30], 2) // returns 20

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