Function Invoke-Keep {
<#
.SYNOPSIS
Implement the keep operation on collections, including nested arrays.
.DESCRIPTION
Given a collection (which may contain nested arrays), apply the predicate to each element and return an array of elements where the predicate is true.
.PARAMETER Data
Collection of data to filter through, can be nested arrays.
.PARAMETER Predicate
The predicate to operate on the data.
.EXAMPLE
$IsSumGreaterThan10 = { param($row) ($row | Measure-Object -Sum).Sum -gt 10 }
Invoke-Keep -Data @(@(1, 2, 3), @(5, 6), @(10, 5), @(7, 3)) -Predicate $IsSumGreaterThan10
Return: @(@(5, 6), @(10, 5), @(7, 3))
#>
在尝试创建上述函数(并使用.EXAMPLE.中的谓词和数据对其进行测试)时,我发现案例1失败,案例2成功,但不清楚原因:
案例1:
[CmdletBinding()]
Param(
[Object[]]$Data,
[ScriptBlock]$Predicate
)
foreach ($item in $Data) {
if ($Predicate.Invoke($Item)) {
return $item
}
}
案例2:
[CmdletBinding()]
Param(
[Object[]]$Data,
[ScriptBlock]$Predicate
)
return $Data | Where-Object {& $Predicate $_}
}
案例1似乎可以很好地处理平面数据,但在传递嵌套数组时什么也不返回。案例2很好地处理了嵌套数组。但是whwhwhwhWhwhwhwh?!
这可能已经得到了答案,但我足够愚蠢,甚至没有语言在搜索框中表达我的问题。