-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path21_OperatorOverloading.ps1
More file actions
67 lines (56 loc) · 2.3 KB
/
21_OperatorOverloading.ps1
File metadata and controls
67 lines (56 loc) · 2.3 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<#
.SYNOPSIS
OOP Reference: Operator Overloading (Workaround)
.DESCRIPTION
Topic: PS has no custom operators — IComparable/IEquatable plus static methods
Category: PS-Specific
Agent Task: Add a static Merge([CryptoKeyPair[]]$keys) method that returns
the strongest non-expired key from the array.
Add Pester tests verifying Sort-Object, -eq, and hashtable keying.
Done Conditions:
- $k1 -eq $k2 works via IEquatable
- Sort-Object uses IComparable (sorts by expiry)
- Hashtable keys deduplicate by KeyId via GetHashCode
- Pester tests pass: Invoke-Pester -Output Detailed
Non-Scope:
- No operator overloading via C# inline types
#>
class CryptoKeyPair : System.IComparable, System.IEquatable[object] {
[string]$KeyId
[datetime]$Expires
[int]$Strength
CryptoKeyPair([string]$id, [int]$strength, [int]$validDays) {
$this.KeyId = $id
$this.Strength = $strength
$this.Expires = [datetime]::UtcNow.AddDays($validDays)
}
[int] CompareTo([object]$other) {
if ($null -eq $other) { return 1 }
return $this.Expires.CompareTo(([CryptoKeyPair]$other).Expires)
}
[bool] Equals([object]$other) {
if ($null -eq $other) { return $false }
if ($other -isnot [CryptoKeyPair]) { return $false }
return $this.KeyId -eq ([CryptoKeyPair]$other).KeyId
}
[int] GetHashCode() { return $this.KeyId.GetHashCode() }
static [bool] IsStrongerThan([CryptoKeyPair]$a, [CryptoKeyPair]$b) {
return $a.Strength -gt $b.Strength
}
static [CryptoKeyPair] SelectStronger([CryptoKeyPair]$a, [CryptoKeyPair]$b) {
return ($a.Strength -ge $b.Strength) ? $a : $b
}
[bool] IsExpired() { return [datetime]::UtcNow -gt $this.Expires }
static [CryptoKeyPair] Merge([CryptoKeyPair[]]$keys) {
if ($null -eq $keys -or $keys.Count -eq 0) { return $null }
$validKeys = $keys | Where-Object { -not $_.IsExpired() }
if ($null -eq $validKeys -or @($validKeys).Count -eq 0) { return $null }
$strongest = $validKeys[0]
foreach ($key in $validKeys) {
if ($key.Strength -gt $strongest.Strength) {
$strongest = $key
}
}
return $strongest
}
}