steveosoule
1/27/2016 - 2:39 AM

JavaScript Memoizer with Fibonacci & Factoral

JavaScript Memoizer with Fibonacci & Factoral

// FROM : JavaScript: The Good Parts - Memoization (pg. 44 - 45)
// Further Reading: https://addyosmani.com/blog/faster-javascript-memoization/

var total = 0;



//
// Fibonacci - Without Memoizer (crashed my browser at 100)
// This is a typical approach to doing producing Fibonacci results
// But it has exponentially poor results for the higher numbers
//

total = 0;
var fibonacci = function(n){
	total++;
	return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
};

for(var i = 0; i <= 10; i++){
	console.log( fibonacci(i) );
}
console.log('Fibonacci - Without Memoizer called ' + total + ' times'); // when i = 10, called 453 times



//
// Using Memoizer
//

//
// Memoizer Helper Function
//
var memoizer = function (memo, formula) {
	var recur = function(n){
		total++;
		var result = memo[n];
		if( typeof result !== 'number' ){
			result = formula(recur, n);
			memo[n] = result;
		}
		return result;
	};
	return recur;
};

//
// Fibonacci - Using Memoizer
// Using the Memoizer, it greatly reduces resource usage
//
total = 0;
var fibonacci = memoizer([0,1], function(recur, n){
	return recur(n - 1) + recur(n - 2);
});

for(var i = 0; i <= 10; i++){
	console.log( fibonacci(i) );
}
console.log('Fibonacci - Using Memoizer called ' + total + ' times'); // when i = 10, called 29 times


//
// Factoral - Using Memoizer
//
total = 0;
var factoral = memoizer([1,1], function(recur, n){
	return n * recur(n - 1);
});
for(var i = 0; i <= 10; i++){
	console.log( factoral(i) );
}
console.log('Factoral - Using Memoizer called ' + total + ' times'); // when i = 10, called 20 times