Last active
September 22, 2017 11:37
-
-
Save KillyMXI/fa5c06aa480e947018c7a095bb56b98f to your computer and use it in GitHub Desktop.
Get N most recent (or by any other value function) files without sorting entire list.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function InsertSorted($array, $item, $maxn, [scriptblock]$valueFunction) { | |
$a = $valueFunction.InvokeReturnAsIs($item); | |
$j = for($i = 0; $i -lt $array.Count; $i++) { | |
$b = $valueFunction.InvokeReturnAsIs($array[$i]); | |
if ($a -lt $b) { $i; break } | |
} | |
if($j -eq $null) { | |
return ($array[0..($array.Count-1)] + $item)[-$maxn..-1]; | |
} elseif($j -eq 0) { | |
if($array.Count -lt $maxn) { | |
return (@() + $item + $array[0..($array.Count-1)]); | |
} else { | |
return $array; | |
} | |
} else { | |
return ($array[0..($j-1)] + $item + $array[($j)..($array.Count-1)])[-$maxn..-1]; | |
} | |
} | |
function Get-MaxN{ | |
[CmdletBinding()] | |
param ( | |
[Parameter(Mandatory=$true, ValueFromPipeline=$true)][PSObject[]]$InputObject, | |
[Parameter(Mandatory=$true)][scriptblock]$ValueFunction, | |
[Parameter(Mandatory=$true)][int]$N | |
) | |
$selected = @(); | |
$Input | foreach { | |
if($selected.Count -eq 0) { | |
$selected = ,$_; | |
} else { | |
$selected = InsertSorted $selected $_ $N $ValueFunction; | |
} | |
} | |
return $selected; | |
} | |
function Get-LastWriteTime([System.IO.FileSystemInfo]$item) { | |
return $item.LastWriteTime; | |
} | |
gci . -file | Get-MaxN -ValueFunction ${function:Get-LastWriteTime} -N 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment