Least Recently Used (LRU) Cache implementation using OrderedDict.
python
from collections import OrderedDict class LRUCache: def __init__(self, capacity: int): self.cache = OrderedDict() self.capacity = capacity def get(self, key: int) -> int: if key not in self.cache: return -1 # Move to end (most recently used) self.cache.move_to_end(key) return self.cache[key] def put(self, key: int, value: int) -> None: if key in self.cache: # If exists, update value and move to end self.cache.move_to_end(key) self.cache[key] = value if len(self.cache) > self.capacity: # Remove least recently used item self.cache.popitem(last=False) # Example usage: cache = LRUCache(2) cache.put(1, 1) cache.put(2, 2) print(cache.get(1)) # returns 1 cache.put(3, 3) # evicts key 2 print(cache.get(2)) # returns -1 (not found) print(cache.get(3)) # returns 3
React hook for debouncing value changes. Sure works well
typescript
import {useEffect, useState} from 'react'; export function useDebounce(value: string, delay = 800) { const [debouncedValue, setDebouncedValue] = useState(value); useEffect(() => { const handler = setTimeout(() => { setDebouncedValue(value); }, delay); return () => { clearTimeout(handler); }; }, [value, delay]); return debouncedValue; }
React hook for debouncing value changes
javascript
An efficient implementation of the Quick Sort algorithm with TypeScript generics.
function quickSort<T>(arr: T[]): T[] { if (arr.length <= 1) return arr; const pivot = arr[Math.floor(arr.length / 2)]; const left = arr.filter(x => x < pivot); const middle = arr.filter(x => x === pivot); const right = arr.filter(x => x > pivot); return [...quickSort(left), ...middle, ...quickSort(right)]; } // Example usage: const numbers = [64, 34, 25, 12, 22, 11, 90]; console.log(quickSort(numbers));