# Elegant memoizing

I wanted an elegant way to implement memoizing. Here is what I came up with:

function memoize(fn) {
var cache = new WeakMap();
return function() {
if (!cache[arguments]) {
cache[arguments] = fn.call(this, arguments);
}
return cache[arguments];
}
}


It's quite nice, but the WeakMap is not well supported. Is there a better, yet clean way to do this?

-

function memoize(fn) {
var cache = {};
return function() {
var args = Array.prototype.slice.call(arguments).toString();
if (!cache[args]) {
cache[args] = fn.call(this, arguments);
}
return cache[args];
}
}


It's very cross-browser. I can't think of any browser not supporting this.

But it does feel kind of ugly. It's still the best I can think of though.

-
This isn't equivalent. There can be collisions. For example, ["a,b"] and ["a", "b] (at least my understanding of Array.toString -- developer.mozilla.org/en-US/docs/JavaScript/Reference/…) –  Corbin Feb 1 '13 at 19:06
Indeed. Then I'm lost :P –  Florian Margaine Feb 1 '13 at 19:08