Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't use the same memoized function across instances when .decorator() is used #75

Merged
merged 5 commits into from
Apr 20, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 32 additions & 2 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import mapAgeCleaner = require('map-age-cleaner');

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

const decoratorInstanceMap = new WeakMap();

const cacheStore = new WeakMap<AnyFunction>();

interface CacheStorageContent<ValueType> {
Expand Down Expand Up @@ -66,6 +68,15 @@ interface Options<
readonly cache?: CacheStorage<CacheKeyType, ReturnType<FunctionToMemoize>>;
}

interface DecoratorOptions {
/**
Whether the same memoized function should be used in different instances or a different one should be initialised for each one.

@default false
*/
readonly isAcrossInstances?: boolean;
}

/**
[Memoize](https://en.wikipedia.org/wiki/Memoization) functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input.

Expand Down Expand Up @@ -170,7 +181,10 @@ mem.decorator = <
FunctionToMemoize extends AnyFunction,
CacheKeyType
>(
options: Options<FunctionToMemoize, CacheKeyType> = {}
{
isAcrossInstances = false,
...options
}: Options<FunctionToMemoize, CacheKeyType> & DecoratorOptions = {}
) => (
target: any,
propertyKey: string,
Expand All @@ -182,7 +196,23 @@ mem.decorator = <
throw new TypeError('The decorated value must be a function');
}

descriptor.value = mem(input, options);
if (isAcrossInstances) {
descriptor.value = mem(input, options);
return;
}

delete descriptor.value;
delete descriptor.writable;

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

return decoratorInstanceMap.get(this);
};
};

/**
Expand Down
9 changes: 8 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,14 @@ Returns a TypeScript decorator which memoizes the given function.

Type: `object`

Same as options for `mem()`.
Same as options for `mem()` and the following:

##### isAcrossInstances
Richienb marked this conversation as resolved.
Show resolved Hide resolved

Type: `boolean`\
Default: `false`

Whether the same memoized function should be used in different instances or a different one should be initialised for each one.

```ts
import mem = require('mem');
Expand Down
28 changes: 24 additions & 4 deletions test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,21 +238,41 @@ test('prototype support', t => {
});

test('.decorator()', t => {
class TestClass {
index = 0;
let returnValue = 1;

class TestClass {
@mem.decorator()
counter() {
return ++this.index;
return returnValue;
}
}

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

returnValue++;

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

returnValue++;

class TestClass2 {
@mem.decorator({isAcrossInstances: true})
counter() {
return returnValue;
}
}

const charlie = new TestClass2();
t.is(charlie.counter(), 3);
t.is(charlie.counter(), 3, 'The method should be memoized');

returnValue++;

const delta = new TestClass2();
t.is(delta.counter(), 3, 'The method should be memoized across instances');
});

test('mem.clear() throws when called with a plain function', t => {
Expand Down