Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

I just thought about 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.

share|improve this answer
    
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.