Monday, November 11, 2013

This is basic concept of Memoization in Javascript

<!DOCTYPE>
<html>
<body>
<script>
<!--  Basic use -->
function square(num){
return num*num;
}

console.log(square(10));

function squareMemoization(num){
var result= '';
if(!squareMemoization.cache[num]){
console.log("computing value..");
result = num * num;
squareMemoization.cache[num]= result;
}

return squareMemoization.cache[num];

}

squareMemoization.cache = {};

console.log(squareMemoization(10)); //First time when we call this function. It calculates the value &amp; cache it.
console.log(squareMemoization(10)); // Second time onwards it return the result from cache.
console.log(squareMemoization(20)); // square function will calculate again if its a new value.


var a = ["a", "b", "c"];


console.log('a.slice(1,2)');
console.log(a.slice(1,2));
console.log('a.slice(1)');
console.log(a.slice(1));
console.log(a);

console.log('Array.prototype.slice.call(a, 1)');
console.log(Array.prototype.slice.call(a, 1));

</script>
</body>
</html>

No comments:

Post a Comment