diff --git a/README.md b/README.md index 88e00ef..e580086 100644 --- a/README.md +++ b/README.md @@ -253,6 +253,8 @@ LRU.forEach((value, key) => { You can set types for both keys and values. For example: ```ts +import { createLRU } from 'lru.min'; + type Key = number; type Value = { @@ -265,6 +267,31 @@ LRU.set(1, { name: 'Peter' }); LRU.set(2, { name: 'Mary' }); ``` +Also: + +```ts +import { createLRU, type CacheOptions } from 'lru.min'; + +type Key = number; + +type Value = { + name: string; +}; + +const options: CacheOptions = { + max: 10, + onEviction(key, value) { + console.log(key, value); + }, +}; + +// No need to repeat the type params +const LRU = createLRU(options); + +LRU.set(1, { name: 'Peter' }); +LRU.set(2, { name: 'Mary' }); +``` + --- ### Performance diff --git a/src/index.ts b/src/index.ts index a7fb968..f406f3b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,9 +1,11 @@ -export const createLRU = (options: { +export type CacheOptions = { /** Maximum number of items the cache can hold. */ max: number; /** Function called when an item is evicted from the cache. */ onEviction?: (key: Key, value: Value) => unknown; -}) => { +}; + +export const createLRU = (options: CacheOptions) => { let { max, onEviction } = options; if (!(Number.isInteger(max) && max > 0)) diff --git a/test/quickstart.test.ts b/test/quickstart.test.ts index 3a27780..a222f71 100644 --- a/test/quickstart.test.ts +++ b/test/quickstart.test.ts @@ -1,5 +1,5 @@ import { describe, it, assert } from 'poku'; -import { createLRU } from '../src/index.ts'; +import { createLRU, type CacheOptions } from '../src/index.ts'; describe('Quickstart example test', () => { it('Default', () => { @@ -139,4 +139,61 @@ describe('Quickstart example test', () => { 'Key "C" with value "Another Value" has been evicted.', ]); }); + + it('Type Test', () => { + const options: CacheOptions = { + max: 10, + onEviction(key, value) { + console.log(key, value); + }, + }; + + createLRU(options); + }); + + it('Type Test: Params on `CacheOptions`', () => { + const options: CacheOptions = { + max: 10, + onEviction(key, value) { + console.log(key, value); + }, + }; + + createLRU(options).set(1, 'Test'); + // @ts-expect-error + createLRU(options).set('2', 'Test'); + }); + + it('Type Test: Params in `createLRU`', () => { + const options: CacheOptions = { + max: 10, + onEviction(key, value) { + console.log(key, value); + }, + }; + + createLRU(options).set(1, 'Test'); + // @ts-expect-error + createLRU(options).set('2', 'Test'); + }); + + it('Type Test: README.md', () => { + type Key = number; + + type Value = { + name: string; + }; + + const options: CacheOptions = { + max: 10, + onEviction(key, value) { + console.log(key, value); + }, + }; + + const LRU = createLRU(options); + + LRU.set(1, { name: 'Peter' }); + LRU.set(2, { name: 'Mary' }); + }); });