Last active
January 25, 2025 21:26
-
-
Save scriptingstudio/43a285099bd0d04b339698f7b988d6d7 to your computer and use it in GitHub Desktop.
Simple numerical series compressor
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 compress-range ([int[]]$inputobject, [switch]$sort, [switch]$unique) { | |
| if (-not $inputobject.count) {return} | |
| $first = $true | |
| $range = $inputobject[0],$inputobject[0] | |
| $param = @{} | |
| if ($unique) {$param['unique'] = $true} | |
| $sb = if ($sort) {{$inputobject | Sort-Object @param}} else {{$inputobject}} | |
| foreach ($e in (.$sb)) { | |
| $diff = [math]::Abs($e - $range[1]) | |
| if ($diff -eq 1) {$range[1]++} | |
| elseif ($first) {$first = $false} # first loop is always true | |
| else { | |
| if ($range[0] -eq $range[1]) {$range[0]} | |
| elseif ([math]::Abs($range[1] - $range[0]) -eq 1) { | |
| $range[0] | |
| $range[1] | |
| } | |
| else {$range[0],$range[1] -join '-'} | |
| $range[0] = $range[1] = $e | |
| } | |
| } | |
| if ($range[0] -eq $range[1]) {$range[0]} | |
| elseif ([math]::Abs($range[1] - $range[0]) -eq 1) { | |
| $range[0] | |
| $range[1] | |
| } | |
| else {$range[0],$range[1] -join '-'} | |
| } # END compress-range |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment