Skip to content

cubiwan/memo.js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Memo.js     Buy Me a Coffee at ko-fi.com

Memoization javascript library

Install

<script src="memo.js"> </script>

Use Memo

let memo = new Memo(function);

Create a memoization for function.

memo.call(parameters);

Call to function.

Example:

function sum(a,b){  
    console.log("calculating "+a+" + "+b);  
    return a+b;  
}  

let memo = new Memo(sum);  

console.log(memo.call(1,2)); //call sum  

console.log(memo.call(1,2)); //no call sum

console.log(memo.call(2,3)); //call sum  

console.log(memo.call(2,1)); //call sum  
memo.getCache();

Return a copy of cache in a string.

memo.loadCache(cache);

Restore cache from a copy.

memo.eraseCache();

Remove cache.

Example:

let storeMemoCache = memo.getCache(); //export cache values to string

let memo2 = new Memo(sum);

memo2.loadCache(storeMemoCache); //load cache

console.log(memo2.call(1,2)); //no call sum
memo.calculateKey(parameters);

Return cache key for parameters.

memo.add(key, value);

Add value to cache.

Example:

memo.add(memo.calculateKey(3,3), 7); //add value 3,3 = 7

console.log(memo.call(3,3)); //no call sum, result 7

Use MemoTime

let memo = new MemoTime(function, duration);

Create a memoization for function with lifetime in miliseconds.

Example:

let memoTime = new MemoTime(sum, 2000);

console.log(memoTime.call(4,5)); //call sum

console.log(memoTime.call(4,5)); //no call sum
setTimeout(memoTime.call(4,5),1000); //no call sum
setTimeout(memoTime.call(4,5),3000); //call sum

Use other function to calculate cache key from parameters

let memo = new Memo(function, keyFunction);
let memoTime = new MemoTime(function, duration, keyFunction);

Example:

let memo3 = new Memo(sum, calculateKeySorted); //calculateKeySorted 

console.log(memo3.call(2,3)); //call sum

console.log(memo3.call(2,3)); //no call sum

console.log(memo3.call(3,2)); //no call sum

Memo.js includes 3 calculate key functions:

function calculateKey(){
    let args = Array.from(arguments);
    return JSON.stringify(args);
}

function calculateKeySorted(){
    let args = Array.from(arguments).sort();    
    return JSON.stringify(args);
}

function calculateKeyToLowerCase(){
    let args = Array.from(arguments);    
    return JSON.stringify(args).toLowerCase();
}

Recursion

Example:

function factorial(n){
    console.log("factorial "+n);
    if(n < 2){
        return 1;
    } else {
        return factorial(n-1);
    }
}

let factM = new Memo(factorial);

factorial = (n) => factM.call(n);

factorial(3);
factorial(5);

About

Memoization javascript library

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published