Last active
June 9, 2021 16:48
-
-
Save hexium310/76a40d80b7014ca29685350d46667335 to your computer and use it in GitHub Desktop.
group-by-range
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
group-by-range() { | |
setopt LOCAL_OPTIONS EXTENDED_GLOB | |
local value | |
local values=(${(ps: :)1}) | |
local separator=${2--} | |
local tmp_separator=, | |
local result=() | |
local positives=(${(no)${(M)values:#[[:digit:]]##}}) | |
local negatives=(${(nO)${(M)values:#-[[:digit:]]##}}) | |
local characters=(${(o)${(M)values:#[^[:digit:]]}}) | |
values=($negatives $positives $characters) | |
for value in ${(u)values}; do | |
if [[ -z ${result[-1]} ]]; then | |
result+=($value) | |
continue | |
fi | |
local last_value=${${result[-1]}#*$tmp_separator} | |
if [[ $value = (|-)[[:digit:]]## ]] && [[ $last_value = (|-)[[:digit:]]## ]] && (( $value == $last_value + 1 )) || | |
([[ $value = [^[:digit:]] ]] && (( $(printf '%d' \'$value) == $(printf '%d' \'$last_value) + 1 ))); then | |
result[-1]="${${result[-1]}%$tmp_separator*}$tmp_separator$value" | |
continue | |
fi | |
result+=($value) | |
done | |
echo ${result//$tmp_separator/$separator} | |
} |
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
$ group-by-range '1 2 3 4 5 8 9 10 13 14 20 22' | |
1-5 8-10 13-14 20 22 | |
$ group-by-range '1 2 3 4 5 8 9 10 13 14 20 22' ',' | |
1,5 8,10 13,14 20 22 | |
$ group-by-range '3 % 4 " γ π # 0 $ 2 ! γ π γ π γ z -1 x γ π y -2 γ 3' | |
-2-0 2-4 !-% x-z γ-γ π-π |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment