Last active
March 17, 2016 11:35
-
-
Save ineentho/3ccaaec164e418f685d7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;(function(){ | |
function hash(str) { | |
// Source: http://stackoverflow.com/a/7616484/502126 | |
var hash = 0, i, chr, len | |
if (str.length === 0) return hash | |
for (i = 0, len = str.length; i < len; i++) { | |
chr = str.charCodeAt(i) | |
hash = ((hash << 5) - hash) + chr | |
hash |= 0 | |
} | |
return hash.toString() | |
} | |
function storeCache(hashCode, translated, format) { | |
localStorage['syscache-' + hashCode + '-code'] = translated | |
localStorage['syscache-' + hashCode + '-format'] = format || 'undefined' | |
} | |
function loadCache(hashCode) { | |
var format = localStorage['syscache-' + hashCode + '-format'] | |
if (format) { | |
return { | |
translated: localStorage['syscache-' + hashCode + '-code'], | |
format: format === 'undefined' ? undefined: format | |
} | |
} | |
return false | |
} | |
System.originalTranslate = System.translate; | |
System.translate = function (load) { | |
var hashCode = hash(load.source) | |
var cache = loadCache(hashCode) | |
if (cache) { | |
load.metadata.format = cache.format | |
return cache.translated | |
} | |
return System.originalTranslate.apply(this, [load]).then(function(translated) { | |
storeCache(hashCode, translated, load.metadata.format) | |
console.log('Cached', load.address) | |
return translated | |
}) | |
} | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Love this idea. I created an IndexedDB variant here.