Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sortAlpha does not work for list of numbers #362

Open
ghahramani opened this issue Feb 17, 2023 · 2 comments
Open

sortAlpha does not work for list of numbers #362

ghahramani opened this issue Feb 17, 2023 · 2 comments

Comments

@ghahramani
Copy link

ghahramani commented Feb 17, 2023

Hi,

I was trying to sort a list of int with sortAlpha and I realized it does not sort it correctly and I found out that it is because of this line https://github.com/Masterminds/sprig/blob/master/list.go#L238 which first converts it to string and then sort it. This is wrong behaviour as it should sort it in the type because then 10 will have precedence over 2. Here is the example that does not sort well

Note: I am using it in the helm chart

{{- (list 0 10 2 4 1 11) | sortAlpha | sortAlpha -}}

The output is

data:[0 1 10 11 2 4]

but it should be

data:[0 1 2 4 10 11]
@chrishalbert
Copy link
Contributor

This is the correct intended behavior. In order to get the behavior you are seeking, there would need to be a sortNumeric function on the lists.

@wi11dey
Copy link

wi11dey commented Mar 10, 2024

Here's a workaround for Helm charts until #392 is merged:

{{- define "sortNumeric" -}}
{{- $strings := list -}}
{{- range $element := . -}}
  {{/* Left-pad with 4 zeros: */}}
  {{- $padded := printf "0000%d" $element -}}
  {{- $padded := trunc (sub 4 (len $padded)) $padded -}}
  {{- $strings := mustAppend $strings $padded -}}
{{- end -}}
{{- $strings := sortAlpha $strings -}}
[{{ join ", " $strings}}]
{{- end -}}

Can be used like

{{ include "sortNumeric" (list 0 10 2 4 1 11) | fromJson }}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants