|
| 1 | +class BookList { |
| 2 | + static [System.Collections.Generic.List[Book]] $Books |
| 3 | + |
| 4 | + static [void] Initialize() { [BookList]::Initialize($false) } |
| 5 | + static [bool] Initialize([bool]$force) { |
| 6 | + if ([BookList]::Books.Count -gt 0 -and -not $force) { |
| 7 | + return $false |
| 8 | + } |
| 9 | + |
| 10 | + [BookList]::Books = [System.Collections.Generic.List[Book]]::new() |
| 11 | + |
| 12 | + return $true |
| 13 | + } |
| 14 | + |
| 15 | + static [void] Validate([Book]$Book) { |
| 16 | + $Prefix = @( |
| 17 | + 'Book validation failed: Book must be defined with the Title,' |
| 18 | + 'Author, and PublishDate properties, but' |
| 19 | + ) -join ' ' |
| 20 | + if ($null -eq $Book) { throw "$Prefix was null" } |
| 21 | + if ([string]::IsNullOrEmpty($Book.Title)) { throw "$Prefix Title wasn't defined" } |
| 22 | + if ([string]::IsNullOrEmpty($Book.Author)) { throw "$Prefix Author wasn't defined" } |
| 23 | + if ([datetime]::MinValue -eq $Book.PublishDate) { throw "$Prefix PublishDate wasn't defined" } |
| 24 | + } |
| 25 | + |
| 26 | + static [void] Add([Book]$Book) { |
| 27 | + [BookList]::Initialize() |
| 28 | + [BookList]::Validate($Book) |
| 29 | + if ([BookList]::Books.Contains($Book)) { throw "Book '$Book' already in list" } |
| 30 | + |
| 31 | + $findPredicate = { |
| 32 | + param([Book]$b) |
| 33 | + |
| 34 | + $b.Title -eq $Book.Title -and |
| 35 | + $b.Author -eq $Book.Author -and |
| 36 | + $b.PublishDate -eq $Book.PublishDate |
| 37 | + }.GetNewClosure() |
| 38 | + if ([BookList]::Books.Find($findPredicate)) { throw "Book '$Book' already in list" } |
| 39 | + |
| 40 | + [BookList]::Books.Add($Book) |
| 41 | + } |
| 42 | + |
| 43 | + static [void] Clear() { |
| 44 | + [BookList]::Initialize() |
| 45 | + [BookList]::Books.Clear() |
| 46 | + } |
| 47 | + |
| 48 | + static [Book] Find([scriptblock]$Predicate) { |
| 49 | + [BookList]::Initialize() |
| 50 | + return [BookList]::Books.Find($Predicate) |
| 51 | + } |
| 52 | + |
| 53 | + static [Book[]] FindAll([scriptblock]$Predicate) { |
| 54 | + [BookList]::Initialize() |
| 55 | + return [BookList]::Books.FindAll($Predicate) |
| 56 | + } |
| 57 | +} |
0 commit comments