Last active
April 2, 2022 21:02
-
-
Save santisq/f96c5ed76f0000b101f92b27164a83ec to your computer and use it in GitHub Desktop.
ways to unroll a nested array
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
| $toUnroll = @(@(0,1),@(2,3),@(@(4,@(5,6)),@(7,8),9),10) | |
| # With a Queue, unordered unrolling | |
| function QueueUnroll { | |
| [cmdletbinding()] | |
| param( | |
| [parameter(Mandatory, ValueFromPipeline)] | |
| [object[]]$Unroll | |
| ) | |
| process { | |
| $queue = [System.Collections.Queue]::new() | |
| $queue.Enqueue($Unroll) | |
| while($queue.Count) { | |
| foreach($item in $queue.Dequeue()) { | |
| if($item -is [object[]]) { | |
| $queue.Enqueue($item) | |
| continue | |
| } | |
| $item | |
| } | |
| } | |
| } | |
| } | |
| QueueUnroll -Unroll $toUnroll | |
| # With a Recursive Function, ordered unrolling | |
| function RecursiveUnroll { | |
| param( | |
| [parameter(Mandatory, ValueFromPipeline)] | |
| [object[]]$Unroll | |
| ) | |
| process { | |
| foreach($item in $Unroll) { | |
| if($item -is [object[]]) { | |
| RecursiveUnroll -Unroll $item | |
| continue | |
| } | |
| $item | |
| } | |
| } | |
| } | |
| RecursiveUnroll -Unroll $toUnroll | |
| # With a Recursive Method, ordered unrolling | |
| class Unroller { | |
| [object[]]$Array | |
| Unroller() { } | |
| Unroller([object[]]$Array) { | |
| $this.Array = $Array | |
| } | |
| static [object] Unroll([object[]]$Array) { | |
| $result = foreach($item in $Array) { | |
| if($item -is [object[]]) { | |
| [Unroller]::Unroll($item) | |
| continue | |
| } | |
| $item | |
| } | |
| return $result | |
| } | |
| [object] Unroll () { | |
| return [Unroller]::Unroll($this.Array) | |
| } | |
| } | |
| $class = [Unroller]$toUnroll | |
| $class.Unroll() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment