Skip to content

Instantly share code, notes, and snippets.

@tianshuo
Created November 26, 2012 08:06
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 tianshuo/4147123 to your computer and use it in GitHub Desktop.
Save tianshuo/4147123 to your computer and use it in GitHub Desktop.
Recursive Fizzbuzz with Y-combinator in javascript
/* Recursive Fizzbuzz with Y-combinator in javascript...
* Tail-recursion and no loops
* By TiansHUo http://tianshuohu.diandian.com
* Y-combinator from: http://blog.jcoglan.com/2008/01/10/deriving-the-y-combinator/
*/
var Y = function(f) {
return (function(g) {
return g(g);
})(function(h) {
return function(n,k) {
return f(h(h))(n,k);
};
});
};
var fizzbuzz=Y(function(f){
return function(n,k){
k=k||[];
if(n>0){
if(n%15==0) {
k.push("fizzbuzz");
}else if(n%3==0){
k.push("fizz");
}else if(n%5==0){
k.push("buzz");
}else{
k.push(n);
}
f(n-1,k);
}else{
return document.write(k.reverse());
}
};
});
fizzbuzz(35);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment