Skip to content

Commit

Permalink
feat(cache): rework expiry systen for set method ans update get / all…
Browse files Browse the repository at this point in the history
… method according to changes
  • Loading branch information
prisca-c committed Dec 23, 2023
1 parent 03a3d95 commit 6c43e7c
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 17 deletions.
33 changes: 23 additions & 10 deletions src/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,32 +7,45 @@ import { CacheInterface } from './types/cache_interface.js'
* @implements {CacheInterface}
*/
export class Cache implements CacheInterface {
protected cache: Map<string, object>
protected cache: Map<string, { value: object; expiry: number }>

constructor() {
this.cache = new Map()
}

get(key: string): object | undefined {
return this.cache.get(key)
const entry = this.cache.get(key)
if (!entry) return undefined

const now = Date.now()
if (now >= entry.expiry) {
console.log('Cache entry expired')
this.cache.delete(key)
return undefined
}
return entry.value
}

set(key: string, value: object, ttl?: number): void {
this.cache.set(key, value)
if (ttl) {
setTimeout(() => {
this.cache.delete(key)
}, ttl)
}
const expiry = ttl ? Date.now() + ttl : Number.POSITIVE_INFINITY
this.cache.set(key, { value, expiry })
}

has(key: string): boolean {
return this.cache.has(key)
}

all(): Array<[string, object]> {
const entries = this.cache.entries()
return [...entries]
const now = Date.now()
return Array.from(this.cache.entries())
.filter(([key, { expiry }]) => {
if (now >= expiry) {
this.cache.delete(key)
return false
}
return true
})
.map(([key, { value }]) => [key, value])
}

delete(key: string): boolean {
Expand Down
19 changes: 12 additions & 7 deletions tests/cache.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { test } from '@japa/runner'

const cache = new Cache()
const key = 'test'
const value = { test: 'test' }
const value = { value: 'test' }

test.group('Cache class', (group) => {
group.each.teardown(() => {
Expand All @@ -29,13 +29,18 @@ test.group('Cache class', (group) => {

test('set() should set a key-value pair with a ttl and delete it after the ttl', async ({
assert,
}) => {
cache.set(key, value, 100)
assert.isTrue(cache.has(key))
}, done) => {
const ttl = 1000
cache.set(key, value, ttl)
let cacheValue = cache.get(key)
assert.deepEqual(cacheValue, value)

setTimeout(() => {
assert.isFalse(cache.has(key))
}, 101)
})
cacheValue = cache.get(key)
assert.isUndefined(cacheValue)
done()
}, ttl + 100) // Wait a bit longer than the TTL to ensure the key-value pair has been removed
}).waitForDone()

test('delete() should delete a key-value pair', async ({ assert }) => {
cache.set(key, value)
Expand Down

0 comments on commit 6c43e7c

Please sign in to comment.