alexreardon/memoize-one

Should `this` be treated as an argument?

alexreardon opened this issue ยท 2 comments

A little context ๐Ÿ˜œ :

// This behaviour is debatable.
it('should memoize the previous result even if the this context changes', () => {
       function getA() {
              return this.a;
       }
       const memoized = memoizeOne(getA);
       const temp1 = {
              a: 20,
              getMemoizedA: memoized,
        };
        const temp2 = {
              a: 30,
              getMemoizedA: memoized,
        };

       expect(temp1.getMemoizedA()).to.equal(20);
       
       // this might be unexpected
       expect(temp2.getMemoizedA()).to.equal(20);
});

The decision is: should this be treated as an argument for the purpose of memoization?

Treat as an argument

(do a comparison between the current context this and the previous execution context lastThis.

Pros:

  • will have expected behaviour in all circumstances

Cons:

  • can accidentally break the cache if the function is invoked in a new context - even if it was not using the context. This might not be a big issue as most of the time the context will be undefined in strict mode unless controlled through using either new, call, apply, bind, or implicit control obj.foo()

Do not treat as an argument

(do not do any context comparison)

Pros:

  • no accidental cache breaks by changing

Cons:

  • functions that use this can have unexpected results (see example above)
  • limit the usage of the library to only functions that do not use this - otherwise there is a chance of invalid results

Alternatives

  • somehow tell the function to consider context as an argument - either opt in or opt out

I am leaning towards considering it as part of memoization invalidation. In strict mode the default context will be undefined unless you really are wanting to control the context in some way. If you are controlling the context then it is safe to assume that the function is context specific and so the context should be treated as an argument.

So people are aware, I have made the decision to treat this as an argument for the reasons listed above. This behaviour is now clearly explained in the readme