Skip to content

Commit

Permalink
Fix using multiple decorators on the same instance (#78)
Browse files Browse the repository at this point in the history
  • Loading branch information
bencehornak authored Jul 17, 2021
1 parent 3b1b8a7 commit 7f7ca0a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
10 changes: 5 additions & 5 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ import mapAgeCleaner from 'map-age-cleaner';

type AnyFunction = (...arguments_: any) => any;

const decoratorInstanceMap = new WeakMap();

const cacheStore = new WeakMap<AnyFunction, CacheStorage<any, any>>();

interface CacheStorageContent<ValueType> {
Expand Down Expand Up @@ -169,6 +167,8 @@ export function memDecorator<
>(
options: Options<FunctionToMemoize, CacheKeyType> = {},
) {
const instanceMap = new WeakMap();

return (
target: any,
propertyKey: string,
Expand All @@ -184,13 +184,13 @@ export function memDecorator<
delete descriptor.writable;

descriptor.get = function () {
if (!decoratorInstanceMap.has(this)) {
if (!instanceMap.has(this)) {
const value = mem(input, options) as FunctionToMemoize;
decoratorInstanceMap.set(this, value);
instanceMap.set(this, value);
return value;
}

return decoratorInstanceMap.get(this) as FunctionToMemoize;
return instanceMap.get(this) as FunctionToMemoize;
};
};
}
Expand Down
11 changes: 8 additions & 3 deletions test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,19 +239,24 @@ test('prototype support', t => {

test('.decorator()', t => {
let returnValue = 1;
const returnValue2 = 101;

class TestClass {
@memDecorator()
counter() {
return returnValue;
return returnValue++;
}

@memDecorator()
counter2() {
return returnValue2;
}
}

const alpha = new TestClass();
t.is(alpha.counter(), 1);
t.is(alpha.counter(), 1, 'The method should be memoized');

returnValue++;
t.is(alpha.counter2(), 101, 'The method should be memoized separately from the other one');

const beta = new TestClass();
t.is(beta.counter(), 2, 'The method should not be memoized across instances');
Expand Down

0 comments on commit 7f7ca0a

Please sign in to comment.