Skip to content

Instantly share code, notes, and snippets.

@dhigginbotham
Last active August 29, 2015 14:21
Show Gist options
  • Save dhigginbotham/3ffb2feef5fcda452e6a to your computer and use it in GitHub Desktop.
Save dhigginbotham/3ffb2feef5fcda452e6a to your computer and use it in GitHub Desktop.

##Silly recursion Some of these may actually suprise you, they suprised me so much I felt the need to actually put this together in some fashion.

###Recursive Fib Can cute code win?

(function(n, w, t) {
  var fib = function(n,arr) { 
    if (!arr) { arr = [1,1]; n=n-2; };
    if (n==-1) return [arr[0]];
    if (n==0) return arr;
    arr.push(arr[arr.length-1] + arr[arr.length-2]);
    return fib(n-1,arr);
  };
  for (var i=2;i<t;) { 
    fib(++i); 
    if ((1+i)%1000==0) {
      console.log(""+ (1+i) + " " + (Date.now() - n) + "ms"); 
    } 
  }
})(Date.now(), window, 15000);

###Recursive Fib w/o ref array Maybe we need to be less cute?

(function(n, w, t) {
  var fib = function(n) { 
    if (!arr) { var arr = [1,1]; n=n-2; };
    if (n==-1) return [arr[0]];
    if (n==0) return arr;
    var proc = function() {
      --n;
      arr.push(arr[arr.length-1] + arr[arr.length-2]);
      return (n==0 ? arr : proc());
    };
    return proc();
  };
  for (var i=2;i<t;) { 
    fib(++i); 
    if ((1+i)%1000==0) {
      console.log(""+ (1+i) + " " + (Date.now() - n) + "ms"); 
    } 
  }
})(Date.now(), window, 15000);

###While loop Well, after running the first two tests you might actually be leaning toward thinking this is our winner?

(function(n, w, t) {
  var fib = function(n) { 
    if (!arr) { var arr = [1,1]; n=n-2; };
    if (n==-1) return [arr[0]];
    if (n==0) return arr;
    while (n>0) {
      --n;
      arr.push(arr[arr.length-1] + arr[arr.length-2]);
    };
    return arr;
  };
  for (var i=2;i<t;) { 
    fib(++i); 
    if ((1+i)%1000==0) {
      console.log(""+ (1+i) + " " + (Date.now() - n) + "ms"); 
    } 
  }
})(Date.now(), window, 15000);

###Recursive Fib w/setTimeout Maybe this will make our cutest example win, well at least not in terms of code smell anyway, fwiw this is hitting about 500k op/s... Insane?

(function(n, w, t) {
  var fib = function(n,arr) { 
    if (!arr) { arr = [1,1]; n=n-2; };
    if (n==-1) return [arr[0]];
    if (n==0) return arr;
    arr.push(arr[arr.length-1] + arr[arr.length-2]);
    w.setTimeout(function() {
      return fib(n-1,arr);
    });
  };
  for (var i=2;i<t;) { 
    fib(++i); 
    if ((1+i)%1000==0) {
      console.log(""+ (1+i) + " " + (Date.now() - n) + "ms"); 
    } 
  }
})(Date.now(), window, 15000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment