Skip to content

Commit

Permalink
add decorator / fix docs/readme / add license
Browse files Browse the repository at this point in the history
  • Loading branch information
vinikjkkj committed Aug 8, 2024
1 parent ffaacbd commit 1fc6521
Show file tree
Hide file tree
Showing 15 changed files with 131 additions and 33 deletions.
7 changes: 7 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright 2024 Vinicius Alves

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ All of most used cache types are included here, if what you are looking for does
//example cache
import { TTLCache } from 'cachetools-js'

const cache = TTLCache({ttl: 1000})
const cache = new TTLCache({ttl: 1000})
```
#### Store a key in cache
```typescript
Expand Down
8 changes: 5 additions & 3 deletions src/caches/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ import { CacheParams, Keyable } from '../types'

/**
* ### About
* Simple cache base class, based in `Proxy` to turn possible to get/set keys like a common object,
* use this class if you want to create a custom cache logic,
* you can use for personal purpose too, but i dont know why
* Simple cache base class, based on `Proxy`, which allows getting and setting keys like a regular object.
*
* This class is useful if you want to create custom cache logic.
*
* It can also be used for personal purposes, although its specific application might not be obvious in all cases.
*
* ### Example
* ```typescript
Expand Down
22 changes: 22 additions & 0 deletions src/caches/decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { CacheLike } from '../types'

export function cacheDecorator
<T extends (...args: any[]) => Promise<any> | any>
(fn: T, cache: CacheLike): T {
return async function (...args: Parameters<T>): Promise<ReturnType<T>> {
const key = args.join('.')

const cachedResult = cache.get(key)
if (cachedResult) {
return cachedResult as ReturnType<T>
}

const result = await fn(...args)

if (cache) {
cache.set(key, result)
}

return result
} as T
}
5 changes: 3 additions & 2 deletions src/caches/fifo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import { MissingSize } from '../utils'

/**
* ### About
* This cache remove values based in **FIFO (First In, First Out)**,
* when cache is full, will remove the first key stored
* This cache remove values based in **FIFO (First In, First Out)**.
*
* When the cache is full, it will remove the first key that was stored.
*
* ### Example
* ```typescript
Expand Down
1 change: 1 addition & 0 deletions src/caches/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ export * from './fifo'
export * from './lfu'
export * from './rrcache'
export * from './pool'
export * from './decorator'
5 changes: 3 additions & 2 deletions src/caches/lfu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import { MissingSize } from '../utils'

/**
* ### About
* This cache remove values based in **LFU (Least Frequently Used)**,
* when cache is full, will remove the key less used
* This cache removes values based on **LFU (Least Frequently Used)**.
*
* When the cache is full, it will remove the least frequently used key.
*
* ### Example
* ```typescript
Expand Down
5 changes: 3 additions & 2 deletions src/caches/lru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import { MissingSize } from '../utils'

/**
* ### About
* This cache remove values based in **LRU (Least Recently Used)**,
* when cache is full, will remove the less recently used key
* This cache removes values based on **LRU (Least Recently Used)**.
*
* When the cache is full, it will remove the least recently used key.
*
* ### Example
* ```typescript
Expand Down
5 changes: 3 additions & 2 deletions src/caches/pool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ import { CacheLike, CachePoolParams, CachesObj, CacheTypes, Keyable, ParamsLike

/**
* ### About
* Pool of caches to store all your caches in a unique variable, making your code more cleaner and easier,
* you can create/get/delete all types of caches, and use standard methods from caches more simplier
* Pool of caches to store all your caches in a single variable, making your code cleaner and easier to manage.
*
* You can create, get, and delete all types of caches, using standard cache methods more simply.
*
* ### Example
* ```typescript
Expand Down
5 changes: 3 additions & 2 deletions src/caches/rrcache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import { MissingSize } from '../utils'

/**
* ### About
* This cache remove values based in **Random Logic**,
* when cache is full, a random key will be removed based in random logic provided
* This cache removes values based on **Random Logic**.
*
* When the cache is full, a random key will be removed according to the provided random logic.
*
* ### Example
* ```typescript
Expand Down
7 changes: 4 additions & 3 deletions src/caches/ttl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import { SizeError } from '../utils'

/**
* ### About
* This cache remove values based in TTL (Time-To-Live),
* if you store a key with TTL of 1 second, in 1 second this key will be removed.
* This cache removes values based on TTL (Time-To-Live).
*
* If you store a key with a TTL of 1 second, that key will be removed after 1 second.
*
* ### Example
* ```typescript
Expand All @@ -18,7 +19,7 @@ import { SizeError } from '../utils'
*
* //custom ttl will be used (500)
* cache.set('bar', 'foo', 500)
*
*
* //store another key
* cache['baz'] = 'foo'
* //throws SizeError, you need to delete some key to store another key
Expand Down
5 changes: 4 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,8 @@ export * from './types'

export {
SizeError,
MissingSize
MissingSize,
AlreadyExists,
CacheNotExists,
CacheTypeNotExists
} from './utils'
27 changes: 22 additions & 5 deletions src/types/params.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,40 @@
export interface CacheParams {
/**Defines the max quantity of keys that will be stored, in some caches this param is required, default is `undefined` */
/**
* Defines the maximum number of keys that will be stored.
* In some caches, this parameter is required; the default is `undefined`.
*/
maxsize?: number
/**If true, will create a **deep copy** of all data before store, default is `false` */

/**
* If true, a **deep copy** of all data will be created before storing.
* The default is `false`.
*/
useClones?: boolean
}

export interface TTLParams extends CacheParams {
/** It's the **Time to Live** of cache in **ms**, if you dont provide `ttl` param in `set` function, this ttl will be used, if not provided, the cache will not delete keys */
/**
* The **Time to Live** of the cache in **ms**.
* If you don't provide the `ttl` parameter in the `set` function, this `ttl` will be used.
* If not provided, the cache will not delete keys.
*/
ttl?: number
}

export interface RRParams extends CacheParams {
/**Random logic for deletion of keys in cache, default is `Math.floor(Math.random * length)` */
/**
* Random logic for the deletion of keys in the cache.
* The default is `Math.floor(Math.random() * length)`.
*/
randomLogic?: (length: number) => number
}

export type ParamsLike = CacheParams | TTLParams | RRParams

export interface CachePoolParams {
/**Defines the max quantity of caches that will be stored, this param is optional, default is `undefined` */
/**
* Defines the maximum number of caches that will be stored.
* This parameter is optional; the default is `undefined`.
*/
maxsize?: number
}
21 changes: 11 additions & 10 deletions src/utils/errors.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,30 @@
export class SizeError extends Error {
constructor(){
super('Tried to set key in cache or pool that is full')
constructor() {
super('Attempted to set a key in a cache or pool that is full.')
}
}

export class MissingSize extends Error {
constructor(){
super('The maxsize param need to be passed in this cache type')
constructor() {
super('The `maxsize` parameter must be provided for this cache type.')
}
}

export class CacheNotExists extends Error {
constructor(){
super('Tried to access cache that not exists in a pool')
constructor() {
super('Attempted to access a cache that does not exist in the pool.')
}
}

export class CacheTypeNotExists extends Error {
constructor(){
super('Cache type passed to \'createCache\' not exists')
constructor() {
super('The cache type passed to `createCache` does not exist.')
}
}

export class AlreadyExists extends Error {
constructor(){
super('This cache already exists')
constructor() {
super('This cache already exists.')
}
}

39 changes: 39 additions & 0 deletions tests/decorator.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Cache, cacheDecorator, CacheLike } from '../src'

describe('Decorator', () => {
let fn: (...args: number[]) => number
let cache: CacheLike
let cachedFunc: (...args: number[]) => number

beforeEach(() => {
fn = (...args) => args.reduce((p, c) => p + c)
cache = new Cache({maxsize: 10})
cachedFunc = cacheDecorator(fn, cache)
})

test('should get a cached value', async () => {
//store a value
await cachedFunc(1, 2, 3)

//get a value
expect(
cache['1.2.3']
).toBe(6)

//use a value
await cachedFunc(1, 2, 3)

//store new value
await cachedFunc(1, 2, 3, 4)

//get a value
expect(
cache['1.2.3.4']
).toBe(10)

//check cache length -- 2 values
expect(
cache.length()
).toBe(2)
})
})

0 comments on commit 1fc6521

Please sign in to comment.