Commit
* Define a general purpose memoize decorator, use it for GM_isGreasemonkeyable() and convert2RegExp().
- Loading branch information
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -326,6 +326,7 @@ function GM_isGreasemonkeyable(url) { | |
|
||
return false; | ||
} | ||
GM_isGreasemonkeyable = GM_memoize(GM_isGreasemonkeyable); | ||
|
||
function GM_getEnabled() { | ||
return GM_prefRoot.getValue("enabled", true); | ||
|
@@ -334,3 +335,30 @@ function GM_getEnabled() { | |
function GM_setEnabled(enabled) { | ||
GM_prefRoot.setValue("enabled", enabled); | ||
} | ||
|
||
// Decorate a function with a memoization wrapper, with a limited-size cache | ||
// to reduce peak memory utilization. Simple usage: | ||
// | ||
// function foo(arg1, arg2) { /* complex operation */ } | ||
// foo = GM_memoize(foo); | ||
// | ||
// The memoized function may have any number of arguments, but they must be | ||
// primitives (able to be used as object keys). | ||
This comment has been minimized.
Sorry, something went wrong.
This comment has been minimized.
Sorry, something went wrong.
arantius
Collaborator
|
||
function GM_memoize(func, limit) { | ||
limit = limit || 1000; | ||
var cache = {}; | ||
This comment has been minimized.
Sorry, something went wrong.
satyr
|
||
var keylist = []; | ||
|
||
return function(a) { | ||
var args = Array.prototype.slice.call(arguments); | ||
if (args in cache) return cache[args]; | ||
|
||
var result = func.apply(null, args); | ||
|
||
cache[args] = result; | ||
keylist.push(args); | ||
while (keylist.length > limit) keylist.shift(); | ||
This comment has been minimized.
Sorry, something went wrong.
erikvold
Contributor
|
||
|
||
return result; | ||
} | ||
} |
This is not entirely correct. Object keys are always strings, so as long as all arguments can be converted to strings, they can be used (so even functions and objects, though using objects is pretty dangerous, since object literals always have the string representation "[object Object]", while objects generated with new Object(x) always have x.toString() as string representation).
This means that the current approach will use the same cached result for foo(2, 3), foo("2,3") and foo(new Object(2), 3).
While this might not be a problem for the current use-cases, I think it might be worth to add a note in the comments.