cue icon indicating copy to clipboard operation
cue copied to clipboard

pkg/math: add Max and Min

Open ethanmdavidson opened this issue 2 years ago • 2 comments

Is your feature request related to a problem? Please describe.

There is no obvious way to get the max or min of two numbers.

The specific usecase I have is truncating a string, e.g.

input: "a string that might be short or long"

if len(strings.Runes(input)) > 63 {
    output: strings.SliceRunes(input, 0, 63)
}
if len(strings.Runes(shortImageVersion)) <= 63 {
    output: input
}

Describe the solution you'd like

Min(x, y Int) and Max(x, y Int) functions added to the std math lib (idk if Int is the appropriate type here)

that would allow:

output: strings.SliceRunes(input, 0, math.Min(63, len(strings.Runes(input))))

Describe alternatives you've considered

In slack someone suggested:

x: 1
y: 2
z: [if x > y {x},y][0]

which is rather opaque and non-intuitive

Additional context

https://cuelang.slack.com/archives/CLT4FD7KP/p1693578715576749

ethanmdavidson avatar Oct 25 '23 15:10 ethanmdavidson

Thanks for raising this, @ethanmdavidson. I agree the alternative is clumsy and unintuitive.

myitcv avatar Oct 26 '23 05:10 myitcv

I believe there is list.Max. Maybe this wasn't available at the time this issue was opened? Is it sufficient?

djahandarie avatar Jun 18 '25 01:06 djahandarie

Yeah, I guess that's not too bad:

strings.SliceRunes(input, 0, list.Min([63, len(strings.Runes(input))]))

I'm happy with closing this, but I'll leave that up to the maintainers.

I don't remember the context in which I opened this issue, but upon rereading it I'm curious why I asked for Max+Min, instead of strings.Truncate. Oh well! the big wheel keeps on turning

ethanmdavidson avatar Jun 18 '25 18:06 ethanmdavidson