← run

js-03-lru-cache

1.000
6/6 tests· data-structures

Proposed solution

```javascript
export class LRUCache {
  constructor(capacity) {
    this.capacity = capacity;
    this.cache = new Map();
  }
  
  get(key) {
    if (!this.cache.has(key)) {
      return undefined;
    }
    
    // Get the value and remove the entry to mark it as most recently used
    const value = this.cache.get(key);
    this.cache.delete(key);
    this.cache.set(key, value);
    
    return value;
  }
  
  put(key, value) {
    // If key exists, delete it to update its position
    if (this.cache.has(key)) {
      this.cache.delete(key);
    } else if (this.cache.size >= this.capacity) {
      // Evict the least recently used entry (first entry in the Map)
      const firstKey = this.cache.keys().next().value;
      this.cache.delete(firstKey);
    }
    
    // Add the new or updated entry
    this.cache.set(key, value);
  }
}
```

Test output (stdout)

TAP version 13
# Subtest: stores and retrieves a value
ok 1 - stores and retrieves a value
  ---
  duration_ms: 0.356502
  type: 'test'
  ...
# Subtest: missing key returns undefined
ok 2 - missing key returns undefined
  ---
  duration_ms: 0.06035
  type: 'test'
  ...
# Subtest: evicts the least-recently-used entry at capacity
ok 3 - evicts the least-recently-used entry at capacity
  ---
  duration_ms: 0.05569
  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.04925
  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.05383
  type: 'test'
  ...
# Subtest: capacity of 1 keeps only the latest entry
ok 6 - capacity of 1 keeps only the latest entry
  ---
  duration_ms: 0.400213
  type: 'test'
  ...
1..6
# tests 6
# suites 0
# pass 6
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 27.751849
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.