Skip to content

Commit

Permalink
feat(esl-utils): add ability to pass multiple memoized props to clear…
Browse files Browse the repository at this point in the history
… at once
  • Loading branch information
fshovchko authored and ala-n committed Dec 6, 2022
1 parent d50e2bb commit 3dca390
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/modules/esl-utils/decorators/memoize.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {defaultArgsHashFn, memoizeFn} from '../misc/memoize';
import {isPrototype, getPropertyDescriptor} from '../misc/object';
import {isPrototype, getPropertyDescriptor, isArrayLike} from '../misc/object';

import type {MemoHashFn} from '../misc/memoize';
import type {MethodTypedDecorator} from '../misc/functions';
Expand Down Expand Up @@ -62,7 +62,9 @@ function memoizeMethod(originalMethod: any, prop: string, hashFn: MemoHashFn) {
* Note: be sure that you targeting memoized property or function.
* Clear utility has no 100% check to prevent modifying incorrect (not memoized) property keys
*/
memoize.clear = function (target: any, property: string): void {
memoize.clear = function (target: any, property: string | string[]): void {
if (isArrayLike(property)) return (property as string[]).forEach((prop) => memoize.clear(target, prop));
property = property as string;
const desc = getPropertyDescriptor(target, property);
if (!desc) return;
if (typeof desc.get === 'function' && typeof (desc.get as any).clear === 'function') return (desc.get as any).clear();
Expand Down
33 changes: 33 additions & 0 deletions src/modules/esl-utils/decorators/test/memoize.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,39 @@ describe('common @memoize decorator test', () => {
});
});

describe('array clear', () => {
const fn = jest.fn();
class TestClass {
@memoize()
test1() {
return fn();
}

@memoize()
test2() {
return fn();
}
}
const instance = new TestClass();

test('cache / clear', () => {
fn.mockReturnValue('a');
expect(instance.test1()).toBe('a');
expect(instance.test2()).toBe('a');
expect(fn).toBeCalledTimes(2);

expect(memoize.has(instance, 'test1')).toBe(true);
expect(memoize.has(instance, 'test2')).toBe(true);
memoize.clear(instance, ['test1', 'test2']);
expect(memoize.has(instance, 'test1')).toBe(false);
expect(memoize.has(instance, 'test2')).toBe(false);

expect(instance.test1()).toBe('a');
expect(instance.test2()).toBe('a');
expect(fn).toBeCalledTimes(4);
});
});

describe('static method', () => {
const fn = jest.fn();
class TestClass {
Expand Down

0 comments on commit 3dca390

Please # to comment.