Skip to content

Instantly share code, notes, and snippets.

@hexium310
Last active June 9, 2021 16:48
Show Gist options
  • Save hexium310/76a40d80b7014ca29685350d46667335 to your computer and use it in GitHub Desktop.
Save hexium310/76a40d80b7014ca29685350d46667335 to your computer and use it in GitHub Desktop.
group-by-range
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}
}
$ 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