Skip to content

Commit

Permalink
feat: handle FIFO replacement policy (#72)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexandrumic committed Feb 6, 2022
1 parent d1bb37f commit 971652b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
20 changes: 15 additions & 5 deletions src/Cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
CacheSize,
CacheTTL
} from './types';
import { addPrefix } from './utils/string';
import { addPrefix, stripPrefix } from './utils/string';

function isExpired(expiryDate: number | string | Date) {
const now = new Date();
Expand All @@ -24,13 +24,13 @@ export class Cache<DataType> {

replacementPolicy: CacheReplacementPolicy;

size?: CacheSize;
size: CacheSize;

constructor(cacheName: string, cacheOptions?: CacheOptions) {
const {
ttl = TTL_1H,
replacementPolicy = 'LRU',
size // TODO add a default size
size = 10 // TODO maybe increase this?
} = cacheOptions ?? {};

this.storage = new Storage();
Expand All @@ -40,14 +40,24 @@ export class Cache<DataType> {
this.size = size;
}

set(key: string, data: DataType) {
async set(key: string, data: DataType) {
const now = new Date();
const payload: CacheObj<DataType> = {
data,
expiryDate: now.setSeconds(now.getSeconds() + this.ttl) // save as Unix timestamp (milliseconds)
};

// TODO implement replacement policies; take into account `size` and `replacementPolicy` type
if (this.replacementPolicy === 'FIFO') {
const allKeys = await this.getAll();

if (allKeys.length >= this.size) {
const sortedList = allKeys.sort((a, b) =>
a.expiryDate > b.expiryDate ? 1 : -1
);

await this.clear(stripPrefix(sortedList[0].key, this.name));
}
}

return this.storage.store(addPrefix(key, this.name), payload);
}
Expand Down
4 changes: 4 additions & 0 deletions src/utils/string.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
export function addPrefix(str: string, prefix: string) {
return `${prefix}${str}`;
}

export function stripPrefix(str: string, prefix: string) {
return str.replace(prefix, '');
}

0 comments on commit 971652b

Please sign in to comment.