Skip to content

Commit

Permalink
feat: Identity serialiser
Browse files Browse the repository at this point in the history
  • Loading branch information
Alorel committed Dec 8, 2023
1 parent d13d629 commit cb8912f
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 2 deletions.
5 changes: 5 additions & 0 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ export function defaultSerialiser(...args: any[]): string {
return JSON.stringify(args);
}

/** @internal */
export function identitySerialiser<T>(value: T): T {
return value;
}

interface Memoised<T, A extends any[], R> extends Fn<T, A, R> {
[MEMOISE_CACHE]: Cache;
}
Expand Down
24 changes: 22 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import type {Cache} from './cache';
import type {Decorator, SerialiserFn} from './core';
import {applyDecorator, defaultSerialiser, MEMOISE_CACHE, memoiseArglessFunction, memoiseFunction} from './core';
import {
applyDecorator,
defaultSerialiser,
identitySerialiser,
MEMOISE_CACHE,
memoiseArglessFunction,
memoiseFunction
} from './core';

/**
* Memoise the method's return value based on call arguments
Expand All @@ -15,7 +22,20 @@ function MemoiseAll<T, R>(): Decorator<T, [], R> {
return applyDecorator(false);
}

export {Memoise, MemoiseAll, MEMOISE_CACHE, defaultSerialiser, memoiseArglessFunction, memoiseFunction};
/** Memoise based on the 1st argument */
function MemoiseIdentity<T, A, R>(): Decorator<T, [A], R> {
return applyDecorator(true, identitySerialiser);
}

export {
Memoise,
MemoiseAll,
MemoiseIdentity,
MEMOISE_CACHE,
defaultSerialiser,
memoiseArglessFunction,
memoiseFunction
};
export type {SerialiserFn, Cache};

declare global {
Expand Down
20 changes: 20 additions & 0 deletions src/test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {expect} from 'chai';
import type {Cache} from './index';
import {MemoiseIdentity} from './index';
import {Memoise, MEMOISE_CACHE, MemoiseAll, memoiseArglessFunction, memoiseFunction} from './index';

/* eslint-disable @typescript-eslint/no-magic-numbers,class-methods-use-this,max-lines-per-function,no-new,max-lines */
Expand Down Expand Up @@ -664,3 +665,22 @@ describe('Memoised functions', () => {
expect(r1).to.not.eq(r4, 'r1 !== r4');
});
});

describe('identity', () => {
class Src {
@MemoiseIdentity()
static foo(x: number) {
return {x};
}
}

const c1 = Src.foo(1);
const c2 = Src.foo(1);
const c3 = Src.foo(0);
const c4 = Src.foo(0);

expect(c1).to.deep.eq({x: 1});
expect(c3).to.deep.eq({x: 0});
expect(c1).to.eq(c2, 'c1 === c2');
expect(c3).to.eq(c4, 'c3 === c4');
});

0 comments on commit cb8912f

Please sign in to comment.