Skip to content

Instantly share code, notes, and snippets.

@thunklife
Created December 18, 2013 21:57
Show Gist options
  • Select an option

  • Save thunklife/8030558 to your computer and use it in GitHub Desktop.

Select an option

Save thunklife/8030558 to your computer and use it in GitHub Desktop.
Some recursive functions...for learning.
var funkshun = (function(){
var concat = Array.prototype.concat;
function replicate(n, x){
return n===0 ? [] : concat.call(replicate(--n, x),x);
}
function take(n, arr){
function _take(n, arr){
var head;
if(n <= 0 || !arr.length) return [];
head = arr.shift();
if(typeof arr[0] === 'function') arr = arr[0]();
return concat.call(head, _take(--n, arr));
}
return _take(n, arr.slice());
}
function reverse(arr){
function _reverse(arr){
var head;
if(!arr.length) return [];
head = arr.shift();
return concat.call(_reverse(arr), head);
}
return _reverse(arr.slice());
}
function maximum(arr){
function _maximum(arr){
var head;
if(!arr.length) throw 'You can\'t get the maximum value of an empty array.';
if(arr.length === 1) return arr[0];
head = arr.pop();
return Math.max(head, _maximum(arr));
}
return _maximum(arr.slice());
}
function repeat(val){
return concat.call(val,function(){return repeat(val);});
}
return{
take: take,
reverse: reverse,
maximum: maximum,
replicate: replicate,
repeat: repeat
};
}());
var arr = [1,2,3,5,4];
var threes = funkshun.repeat(3);
console.log(funkshun.take(500, threes));
console.log(funkshun.maximum([2,4,6,1,7,20,3,0]));
console.log(funkshun.take(3, arr));
console.log(funkshun.replicate(10, 0));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment