PowerShell LRU Cache Class with Bounded Capacity
PowerShell
class LruCache {
[int]$Capacity
[System.Collections.Specialized.OrderedDictionary]$Items = [System.Collections.Specialized.OrderedDictionary]::new()
LruCache([int]$capacity) { $this.Capacity = $capacity }
[object] Get([string]$key) {
if (-not $this.Items.Contains($key)) { return $null }
$value = $this.Items[$key]
$this.Items.Remove($key); $this.Items.Add($key, $value) # refresh recency
return $value
}
[void] Set([string]$key, [object]$value) {
if ($this.Items.Contains($key)) { $this.Items.Remove($key) }
elseif ($this.Items.Count -ge $this.Capacity) { $this.Items.RemoveAt(0) }
$this.Items.Add($key, $value)
}
}