Skip to content

Instantly share code, notes, and snippets.

@dehypnosis
Last active January 15, 2021 18:37
Show Gist options
  • Save dehypnosis/03ca8cf64a704b18651f3dde4f8d2fe2 to your computer and use it in GitHub Desktop.
Save dehypnosis/03ca8cf64a704b18651f3dde4f8d2fe2 to your computer and use it in GitHub Desktop.
js memorize function
// memorization for performance; don't use this for mutable function
function memorize(fun) {
const cache = {};
return function(){
const args = Array.prototype.slice.call(arguments);
const key = JSON.stringify(args);
// fetch
let hit = cache[key];
if (typeof hit != 'undefined') {
return typeof hit == 'object' && hit !== null
? JSON.parse(JSON.stringify(hit))
: hit
}
// put
let result = fun.apply(this, args);
cache[key] = result;
setTimeout(() => { delete cache[key]; }, 3600000); // ttl is 1 hour
return typeof result == 'object' && result !== null
? JSON.parse(JSON.stringify(result))
: result
}
}
@dehypnosis
Copy link
Author

dehypnosis commented Nov 28, 2017

usage

const fun = memorize(someExpentsiveFunction);
fun(...)

in practice

const numberFormat = memorize(function numberFormat(number, decimals, dec_point, thousands_sep) {
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        toFixedFix = function (n, prec) {
            // Fix for IE parseFloat(0.55).toFixed(0) = 0;
            var k = Math.pow(10, prec);
            return Math.round(n * k) / k;
        },
        s = (prec ? toFixedFix(n, prec) : Math.round(n)).toString().split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
})

numberFormat(10000.123); // calculated
numberFormat(10000.123); // from cache

caveat

  • Cannot adapted to mutable/non-pure function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment