classes/PSObjectCache.class.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using namespace System.Collections

class PSObjectCache
{
    hidden [IDictionary]$LookupTable 
    hidden [scriptblock]$Fetcher

    PSObjectCache([scriptblock]$Fetcher){
        $this.Fetcher = $Fetcher
        $this.LookupTable = @{}
    }

    [psobject]Get($Key){
        if($this.LookupTable.Contains($Key)){
            return $this.LookupTable[$Key]
        }
        else{
            try{
                $copy = & $this.Fetcher $Key
                return ($this.LookupTable[$Key] = $copy)
            }
            catch{
                $this.LookupTable.Remove($Key)
                throw $_
            }
            return $null
        }
    }

    [void]AddOrUpdate($Key,$Item){
        $this.LookupTable[$Key] = $Item
    }
    
    [void]Remove($Key){
        $this.LookupTable.Remove($Key)
    }

    [void]Remove([scriptblock]$KeyPredicate){
        foreach($key in $this.LookupTable.Keys.Where($KeyPredicate)){
            $this.Remove($key)
        }
    }
    
    [void]Clear(){
        $this.LookupTable.Clear()
    }
}