Skip to content

Instantly share code, notes, and snippets.

@justinobney
Last active August 29, 2015 14:09
Show Gist options
  • Select an option

  • Save justinobney/651dbd0a6e07948d0f6f to your computer and use it in GitHub Desktop.

Select an option

Save justinobney/651dbd0a6e07948d0f6f to your computer and use it in GitHub Desktop.

Revisions

  1. justinobney revised this gist Nov 14, 2014. 1 changed file with 24 additions and 0 deletions.
    24 changes: 24 additions & 0 deletions timed_cache.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    // This will keep it in the cache unless
    // it is older than 5 seconds

    var cache = {};
    function checkCache(key){
    var now = +new Date();

    var found = cache[key];
    if(found && isNotOld(now, found.ts)){
    return cache[key];
    } else {
    cache[key] = {
    val: Math.random(),
    ts: +new Date()
    };

    return cache[key];
    }
    }

    function isNotOld(t1, t2){
    var lifetime = 5000;
    return Math.abs(t1-t2) < 5000
    }
  2. justinobney created this gist Nov 14, 2014.
    11 changes: 11 additions & 0 deletions simple_cache.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,11 @@
    var cache = {};
    function checkCache(key){
    if(cache[key]){
    return cache[key];
    } else {
    // do some long/expensive action
    // ex: calculation, ajax, etc...
    cache[key] = Math.random();
    return cache[key];
    }
    }