Skip to content

Instantly share code, notes, and snippets.

@davidjbeveridge
Last active August 29, 2015 14:14
Show Gist options
  • Save davidjbeveridge/09e782b2741c6f85d9f7 to your computer and use it in GitHub Desktop.
Save davidjbeveridge/09e782b2741c6f85d9f7 to your computer and use it in GitHub Desktop.
anonymous [memoized] fibonacci range, using y-combinator in JavaScript
(function(Y, memoize){
return (function(range, map, fib) {
return function(a, b) {
return map(fib, range(a, b));
};
})(
Y(function(range, a, b, inc) {
inc = inc || 1;
if(a === b) return [a];
return [a].concat(range(range, a+1, b));
}),
Y(function(map, fn, arr) {
if(!arr.length) return [];
return [fn(arr[0])].concat(map(map, fn, arr.slice(1)));
}),
Y(memoize(function(fib, num) {
if(num < 2) return 1;
return fib(fib, num-2)+fib(fib, num-1);
}))
);
})(
function(fn) {
return function() {
var args = [].slice.call(arguments);
return fn.apply(null, [fn].concat(args));
};
},
function(fn) {
var memo = {};
return function() {
var args = [].slice.call(arguments),
key = args.join(',');
return memo[key] || (memo[key] = fn.apply(null, args));
};
}
)(0, 100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment