Skip to content

Instantly share code, notes, and snippets.

@arch-jslin
Created May 25, 2010 15:41
Show Gist options
  • Save arch-jslin/413281 to your computer and use it in GitHub Desktop.
Save arch-jslin/413281 to your computer and use it in GitHub Desktop.
var memoizer = function (memo, fundamental) {
var make_query = function(args) {
var i = 0, query = '';
for( ; i < args.length - 1 ; i += 1 ) {
query += args[i] + ',';
}
query += args[i]; // i == args.length - 1
return query;
};
var shell = function () {
var args = Array.prototype.slice.apply(arguments);
var query = make_query(args);
var result = memo[ query ];
if ( result === undefined ) {
result = fundamental.apply(null, [shell].concat(args) );
memo[ query ] = result;
document.writeln('<br>caching: ('+query+')='+result);
}
return result;
};
return shell;
};
//arguments[1] is m, arguments[2] is n
var ack = memoizer({}, function(shell, m, n) {
if( m === 0 ) return n + 1;
if( m === 1 ) return n + 2; //special case
if( m === 2 ) return n*2 + 3; //special case
if( m === 3 ) return Math.pow(2, n+3) - 3; //special case
if( m > 0 && n === 0 ) return shell(m-1, 1);
if( m > 0 && n > 0 ) return shell(m-1, shell(m, n-1) );
return NaN; //you shouldn't get this.
});
document.writeln( ack(4,2) ); //This will just resolve to infinity .........
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment