Last active
July 4, 2024 14:03
-
-
Save scriptingstudio/cc3ae1fb43331f14f1ebdb735c136751 to your computer and use it in GitHub Desktop.
Concept demo: array shift
This file contains 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
<# | |
$step < 0 - left shift | |
$step = 0 - reverse | |
$step > 0 - right shift | |
#> | |
function Shift-Array { | |
[cmdletBinding()] | |
param ( | |
[Parameter(ValueFromPipeline)] | |
$Inputobject, | |
[int]$Step | |
) | |
begin {$collection = [System.Collections.Generic.List[object]]::new()} | |
process { | |
if ($InputObject -ne $null) {$collection.addrange(@($InputObject))} | |
} | |
end { | |
if ($collection.count -lt 2) {return $collection} # it takes two or more to shift | |
$alength = $collection.count | |
if (-not $step) {$step = $alength-1} # default | |
# prevent extra loops; adjust shift step | |
if ($step -gt 0 -and $step -gt $alength) {$step = $step % $alength} | |
elseif ($step -lt 0 -and -$step -gt $alength) {$step = $step % $alength} | |
$ustep = [math]::abs($step) | |
if ($ustep -eq $alength) { # 360deg : start = stop | |
return $collection | |
} elseif ($ustep -eq ($alength-1)) { # default | |
[array]::Reverse($collection) | |
return $collection | |
} | |
if ($step -lt 0) { # left shift | |
for ($s=-$step; $s -gt 0; $s--) { | |
$first = $collection[0] | |
for ($i=1; $i -lt $alength; $i++) { | |
$collection[$i-1] = $collection[$i] | |
} | |
$collection[-1] = $first | |
} | |
} | |
else { # right shift | |
for ($s=$step; $s -gt 0; $s--) { | |
$last = $collection[-1] | |
for ($i=$alength-1; $i -gt 0; $i--) { | |
$collection[$i] = $collection[$i-1] | |
} | |
$collection[0] = $last | |
} | |
} | |
$collection | |
} # end | |
} # END Shift-Array |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would suggest change testing on $null.
Or
place $null in the begin
if ($InputObject -ne $null) {$collection.addrange(@($InputObject))}
into
if ($null -ne $InputObject) {$collection.addrange(@($InputObject))}
Or
if ([string]::NotNullOrEmpty($InputObject)) {$collection.addrange(@($InputObject))}