← run

js-03-lru-cache

1.000
6/6 tests· data-structures

Proposed solution

```js
export class LRUCache {
  constructor(capacity) {
    this.capacity = capacity;
    this.cache = new Map();
  }

  get(key) {
    if (!this.cache.has(key)) {
      return undefined;
    }
    const value = this.cache.get(key);
    this.cache.delete(key);
    this.cache.set(key, value);
    return value;
  }

  put(key, value) {
    if (this.cache.has(key)) {
      this.cache.delete(key);
    }
    this.cache.set(key, value);
    if (this.cache.size > this.capacity) {
      const leastRecentlyUsedKey = this.cache.keys().next().value;
      this.cache.delete(leastRecentlyUsedKey);
    }
  }
}
```

Test output (stdout)

TAP version 13
# Subtest: stores and retrieves a value
ok 1 - stores and retrieves a value
  ---
  duration_ms: 0.380874
  type: 'test'
  ...
# Subtest: missing key returns undefined
ok 2 - missing key returns undefined
  ---
  duration_ms: 0.05969
  type: 'test'
  ...
# Subtest: evicts the least-recently-used entry at capacity
ok 3 - evicts the least-recently-used entry at capacity
  ---
  duration_ms: 0.048951
  type: 'test'
  ...
# Subtest: get refreshes recency so a different key is evicted
ok 4 - get refreshes recency so a different key is evicted
  ---
  duration_ms: 0.046901
  type: 'test'
  ...
# Subtest: updating an existing key does not grow size and refreshes recency
ok 5 - updating an existing key does not grow size and refreshes recency
  ---
  duration_ms: 0.05462
  type: 'test'
  ...
# Subtest: capacity of 1 keeps only the latest entry
ok 6 - capacity of 1 keeps only the latest entry
  ---
  duration_ms: 0.457344
  type: 'test'
  ...
1..6
# tests 6
# suites 0
# pass 6
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 31.808435
System prompt
You are an expert programmer. Solve the task exactly as specified. Output your solution as fenced code blocks using the required file name(s) and the exact function/type signatures requested. Prefer correctness; do not include prose outside code unless asked.