Add a helper util.memoize

(imported from commit 16b5c49580e30a51583bc0bc8b11293bba595b3a)
This commit is contained in:
Keegan McAllister 2013-02-15 23:22:18 -05:00
parent 97b6c1f9ca
commit da7f6e0fe8
1 changed files with 19 additions and 0 deletions

View File

@ -91,5 +91,24 @@ exports.destroy_first_run_message = function () {
$('#first_run_message').remove(); $('#first_run_message').remove();
}; };
// Takes a one-argument function. Returns a variant of that
// function which caches result values.
//
// Since this uses a JavaScript object as the cache structure,
// arguments with the same string representation will be
// considered equal.
exports.memoize = function (fun) {
var table = {};
return function (arg) {
// See #351; we should have a generic associative data
// structure instead.
if (! Object.prototype.hasOwnProperty.call(table, arg)) {
table[arg] = fun(arg);
}
return table[arg];
};
};
return exports; return exports;
}()); }());