Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
135 changes: 135 additions & 0 deletions web/src/app/common/lru-cache.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/**
* Copyright 2026 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { LRUCache } from './lru-cache';

describe('LRUCache', () => {
it('should throw error if capacity is less than or equal to 0', () => {
expect(() => new LRUCache(0)).toThrowError(
'Capacity must be greater than 0.',
);
expect(() => new LRUCache(-1)).toThrowError(
'Capacity must be greater than 0.',
);
});

it('should put and get values', () => {
const cache = new LRUCache<string, number>(3);
cache.put('a', 1);
cache.put('b', 2);
expect(cache.get('a')).toBe(1);
expect(cache.get('b')).toBe(2);
expect(cache.get('c')).toBeUndefined();
});

it('should update value and MRU on put of existing key', () => {
const cache = new LRUCache<string, number>(2);
cache.put('a', 1);
cache.put('b', 2);

// Update 'a', making it MRU. 'b' becomes LRU.
cache.put('a', 3);
expect(cache.get('a')).toBe(3);

// Add 'c'. Should evict 'b' (LRU).
cache.put('c', 4);
expect(cache.get('b')).toBeUndefined();
expect(cache.get('a')).toBe(3);
expect(cache.get('c')).toBe(4);
});

it('should call onDispose when item is evicted', () => {
const onDispose = jasmine.createSpy('onDispose');
const cache = new LRUCache<string, number>(2, onDispose);
cache.put('a', 1);
cache.put('b', 2);

cache.put('c', 3);
expect(onDispose).toHaveBeenCalledWith(1); // 'a' was evicted
expect(onDispose).toHaveBeenCalledTimes(1);
});

it('should call onDispose when item is overwritten with different value', () => {
const onDispose = jasmine.createSpy('onDispose');
const cache = new LRUCache<string, number>(2, onDispose);
cache.put('a', 1);

cache.put('a', 2);
expect(onDispose).toHaveBeenCalledWith(1);
expect(onDispose).toHaveBeenCalledTimes(1);

cache.put('a', 2);
expect(onDispose).toHaveBeenCalledTimes(1);
});

it('should call onDispose for all items on clear', () => {
const onDispose = jasmine.createSpy('onDispose');
const cache = new LRUCache<string, number>(2, onDispose);
cache.put('a', 1);
cache.put('b', 2);

cache.clear();
expect(onDispose).toHaveBeenCalledWith(1);
expect(onDispose).toHaveBeenCalledWith(2);
expect(onDispose).toHaveBeenCalledTimes(2);
expect(cache.size).toBe(0);
});

it('should check existence with has without updating MRU', () => {
const cache = new LRUCache<string, number>(2);
cache.put('a', 1);
cache.put('b', 2);

expect(cache.has('a')).toBeTrue();
expect(cache.has('c')).toBeFalse();

cache.put('c', 3);

// 'a' should be evicted because 'has' does NOT update MRU
expect(cache.get('a')).toBeUndefined();
expect(cache.get('b')).toBe(2);
expect(cache.get('c')).toBe(3);
});

it('should return correct size', () => {
const cache = new LRUCache<string, number>(2);
expect(cache.size).toBe(0);
cache.put('a', 1);
expect(cache.size).toBe(1);
cache.put('b', 2);
expect(cache.size).toBe(2);
cache.put('c', 3); // Evicts 'a', size remains 2
expect(cache.size).toBe(2);
cache.clear();
expect(cache.size).toBe(0);
});

it('should iterate with foreach', () => {
const cache = new LRUCache<string, number>(3);
cache.put('a', 1);
cache.put('b', 2);

const keys: string[] = [];
const values: number[] = [];
cache.forEach((val, key) => {
keys.push(key);
values.push(val);
});

expect(keys).toEqual(['a', 'b']);
expect(values).toEqual([1, 2]);
});
});
136 changes: 136 additions & 0 deletions web/src/app/common/lru-cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
/**
* Copyright 2026 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
* A generic Least Recently Used (LRU) cache implementation.
* * This implementation leverages the native JavaScript `Map` object, which preserves
* the insertion order of keys. This allows for O(1) time complexity for both
* read (`get`) and write (`put`) operations.
* * @typeParam K - The type of the keys held in the cache.
* @typeParam V - The type of the values held in the cache.
*/
export class LRUCache<K, V> {
/**
* The underlying store for cache items.
* `Map` maintains the order of entries: the first item is the LRU (Least Recently Used),
* and the last item is the MRU (Most Recently Used).
*/
private readonly cache: Map<K, V> = new Map<K, V>();

/**
* Creates an instance of LRUCache.
* * @param capacity - The maximum number of entries allowed in the cache. Must be a positive integer.
* @throws {Error} If the capacity is less than or equal to 0.
*/
constructor(
private readonly capacity: number,
private onDispose?: (value: V) => void,
) {
if (capacity <= 0) {
throw new Error('Capacity must be greater than 0.');
}
}

/**
* Retrieves the value associated with the specified key.
* * If the key exists, the entry is marked as the most recently used (MRU)
* by moving it to the end of the internal Map.
* * @param key - The key of the element to return.
* @returns The value associated with the key, or `undefined` if the key does not exist.
*/
public get(key: K): V | undefined {
if (!this.cache.has(key)) {
return undefined;
}

// Retrieve the value before deleting
const value = this.cache.get(key)!;

this.cache.delete(key);
this.cache.set(key, value);

return value;
}

/**
* Adds or updates an element with the specified key and value.
* * - If the key already exists, its value is updated and it is marked as most recently used (MRU).
* - If the key does not exist and the cache is full, the least recently used (LRU) item
* (the first item in the Map) is evicted before adding the new item.
* * @param key - The key to add or update.
* @param value - The value to store.
*/
public put(key: K, value: V): void {
if (this.cache.has(key)) {
// Remove the existing entry so it can be re-inserted at the end
const oldValue = this.cache.get(key)!;
if (oldValue !== value && this.onDispose) {
this.onDispose(oldValue);
}
this.cache.delete(key);
} else if (this.cache.size >= this.capacity) {
// Evict the least recently used item (the first key in the iterator)
// Map.prototype.keys() returns an iterator in insertion order.
const lruKey = this.cache.keys().next().value;

// Strict check although lruKey should be present if size > 0
if (lruKey !== undefined) {
if (this.onDispose) {
this.onDispose(this.cache.get(lruKey)!);
}
this.cache.delete(lruKey);
}
}

// Insert the new key-value pair at the end (MRU position)
this.cache.set(key, value);
}
Comment thread
kyasbal marked this conversation as resolved.

/**
* Checks if a key exists in the cache without updating its recentness.
* * @param key - The key to check.
* @returns `true` if the key exists, `false` otherwise.
*/
public has(key: K): boolean {
return this.cache.has(key);
}

/**
* Returns the number of elements currently in the cache.
* * @returns The current size of the cache.
*/
public get size(): number {
return this.cache.size;
}

/**
* Iterates over the cache entries.
* @param callback - The callback function to execute for each entry.
*/
public forEach(callback: (value: V, key: K) => void): void {
this.cache.forEach(callback);
}

/**
* Removes all elements from the cache.
*/
public clear(): void {
if (this.onDispose) {
this.cache.forEach((v) => this.onDispose?.(v));
}
this.cache.clear();
}
Comment thread
kyasbal marked this conversation as resolved.
}
79 changes: 79 additions & 0 deletions web/src/app/common/misc-util.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/**
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { bisectLeft, bisectRight } from './misc-util';

describe('misc-util', () => {
describe('bisectLeft', () => {
it('should return 0 for empty array', () => {
expect(bisectLeft([], 1)).toBe(0);
});

it('should return 0 if value is smaller than all elements', () => {
expect(bisectLeft([1, 2, 3], 0)).toBe(0);
});

it('should return length if value is larger than all elements', () => {
expect(bisectLeft([1, 2, 3], 4)).toBe(3);
});

it('should return index of first occurrence if value exists', () => {
expect(bisectLeft([1, 2, 2, 2, 3], 2)).toBe(1);
});

it('should return insertion point if value does not exist', () => {
expect(bisectLeft([1, 3, 5], 2)).toBe(1);
expect(bisectLeft([1, 3, 5], 4)).toBe(2);
});

it('should respect custom lo and hi', () => {
// search in [3, 5] (indices 1 to 3)
expect(bisectLeft([1, 3, 5, 7], 4, 1, 3)).toBe(2);
// search in [1, 3] (indices 0 to 2)
expect(bisectLeft([1, 3, 5, 7], 2, 0, 2)).toBe(1);
});
});

describe('bisectRight', () => {
it('should return 0 for empty array', () => {
expect(bisectRight([], 1)).toBe(0);
});

it('should return 0 if value is smaller than all elements', () => {
expect(bisectRight([1, 2, 3], 0)).toBe(0);
});

it('should return length if value is larger than all elements', () => {
expect(bisectRight([1, 2, 3], 4)).toBe(3);
});

it('should return index after last occurrence if value exists', () => {
expect(bisectRight([1, 2, 2, 2, 3], 2)).toBe(4);
});

it('should return insertion point if value does not exist', () => {
expect(bisectRight([1, 3, 5], 2)).toBe(1);
expect(bisectRight([1, 3, 5], 4)).toBe(2);
});

it('should respect custom lo and hi', () => {
// search in [3, 5] (indices 1 to 3)
expect(bisectRight([1, 3, 5, 7], 4, 1, 3)).toBe(2);
// search in [1, 3] (indices 0 to 2)
expect(bisectRight([1, 3, 5, 7], 2, 0, 2)).toBe(1);
});
});
});
Loading