Fibonacci with LRUCache

Sunday, February 19th 2023
const fibonacciCache = new LRUCache(10); function fibonacci(n) { if (n < 2) { return n; } const cachedValue = fibonacciCache.get(n); if (cachedValue !== null) { return cachedValue; } const result = fibonacci(n - 1) + fibonacci(n - 2); fibonacciCache.put(n, result); return result; } console.log(fibonacci(10)); // 55 console.log(fibonacci(11)); // 89 console.log(fibonacci(10)); // 55 (returned from cache) console.log(fibonacciCache.getSize()); // 2

In this example, we create a new LRUCache object with a maximum size of 10. We define a fibonacci function that computes the nth Fibonacci number recursively, but uses the LRUCache object to cache previously computed results to avoid redundant computations. When the function is called with a value of n, it first checks if the result for that value is already in the cache. If it is, the function simply returns the cached value. Otherwise, it computes the result recursively, stores it in the cache using the put method of the LRUCache object, and returns the result. We then call the fibonacci function multiple times with different arguments to demonstrate that the cache works correctly. Finally, we print the size of the cache using the getSize method of the LRUCache object to confirm that only two items are stored in the cache after the calls to the fibonacci function.