Skip to content

Commit

Permalink
feat(rr-cache): update interface, readme, rework stats method
Browse files Browse the repository at this point in the history
  • Loading branch information
zhibirc committed Nov 27, 2023
1 parent bc85922 commit 2d2712a
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 6 deletions.
9 changes: 6 additions & 3 deletions rr-cache/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,11 @@ class RRCache implements IRRCache {
this.#store = new Map();
}

get size() {
return this.#store.size;
get stats() {
return {
size: this.#store.size,
capacity: this.#capacity
};
}

set capacity (value: number) {
Expand All @@ -44,7 +47,7 @@ class RRCache implements IRRCache {
return null;
}

store (key: any, value: any) {
add (key: any, value: any) {
let keyIndex: number;

// check if cache capacity limit is reached
Expand Down
18 changes: 17 additions & 1 deletion rr-cache/readme.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,20 @@
# Random Replacement (RR) cache
# Random Replacement (RR) Cache

## Definition

## Implementation details

| Operation | Time complexity | Space complexity | Description |
|------------|-----------------|------------------|-------------------------------------------|
| `stats` | $O(1)$ | $O(1)$ | Get cache statistics. |
| `capacity` | $$ | $$ | Set new capacity value. |
| `read` | $O(1)$ | $O(1)$ | Read value by its key. |
| `add` | $O(1)$ | $O(1)$ | Add value by corresponding key. |
| `has` | $O(1)$ | $O(1)$ | Check if there is a value by given key. |
| `remove` | $O(1)$ | $O(1)$ | Remove value by associated key. |
| `clear` | $O(1)$ | $O(1)$ | Remove cached data and release resources. |

## General theory

Random replacement policy selects a cached item randomly for eviction when the cache is full. It doesn’t consider access patterns or usage history.

Expand Down
19 changes: 17 additions & 2 deletions rr-cache/types.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,25 @@
type TStats = {
// get number of cache entries
size: number;
// get current value of cache capacity
capacity: number;
// @todo: may contain other props like cache misses, etc.
};

interface IRRCache {
get size(): number;
// get cache statistics
get stats(): TStats;
// set new capacity value
set capacity(value: number);
// read value from cache by its key
read: (key: any) => any;
store: (key: any, value: any) => void;
// add value to cache by corresponding key
add: (key: any, value: any) => void;
// check if cache contains value by given key
has: (key: any) => boolean;
// remove value from cache by associated key
remove: (key: any) => void;
// clear cache by removing all stored data and release all auxiliary resources
clear: () => void;
};

Expand Down

0 comments on commit 2d2712a

Please sign in to comment.