diff --git a/functional.psm1 b/functional.psm1 index 5af1283..480a9a1 100644 --- a/functional.psm1 +++ b/functional.psm1 @@ -186,7 +186,8 @@ function Reduce-Object { [ValidateNotNullOrEmpty()] [object[]] $Object, [ParamStyle] $ParamStyle = "Infer", - [Direction] $Direction = "Right" + [Direction] $Direction = "Right", + [object] $InitialValue = $null ) # deduce and validate scriptblock invokation style @@ -203,9 +204,10 @@ function Reduce-Object { } # invoke the reducer - $accum = $input | Select -First 1 + $accum = if ($null -eq $InitialValue) { $input | Select -First 1 } else { $InitialValue } if ($implicit) { - foreach ($object in $input | Select -Skip 1) { + $iterated = if ($null -eq $InitialValue) { $input | Select -Skip 1 } else { $input } + foreach ($object in $iterated) { # invoke in scriptblock to minimize exposure of local variables $safelyScoped = { Param($a, $b, [scriptblock]$reducer) diff --git a/functional.tests.ps1 b/functional.tests.ps1 index c0392ac..89061ab 100644 --- a/functional.tests.ps1 +++ b/functional.tests.ps1 @@ -26,6 +26,10 @@ Describe "Reduce-Object" { It "Should not throw for explicit params and 'Infer'" { { 1..10 | Reduce-Object { Param($a, $b); $a + $b } -ParamStyle "Infer" } | Should -Not -Throw } + It "Should use initial value parameter if provided" { + $result = @("Joey","Jhonny","Dee Dee")| Reduce-Object { $a+= @{$b = $b.Length}; $a } -InitialValue @{} + $result, ${ "Joey" = 4; "Jhonny" = 6 ; "Dee Dee" = 7 } | Test-Equality | Should -BeTrue + } } Context "Given an implicit sum reducer" { It "Should sum up the numbers" {