summary refs log tree commit diff stats
path: root/lib
diff options
context:
space:
mode:
authorMatt Wilson <matt@culturethree.com>2023-05-12 18:02:09 +1200
committerGitHub <noreply@github.com>2023-05-12 14:02:09 +0800
commitea39c600abcb8853791404145c3038ea9488d0f4 (patch)
tree136b94bf1d92bfad7e2eb57405b569cb035dbd68 /lib
parent9810b8cf7ff85a306699d8393ce516501d938e05 (diff)
downloadNim-ea39c600abcb8853791404145c3038ea9488d0f4.tar.gz
Add `minmax` to comparisons (#21820)
* Add `minmax` to sequtils

This adds a `minmax` proc to complement `min` and `max`; it computes
both results in a single pass for efficiency.

* Update lib/pure/collections/sequtils.nim

* Add minmax note to changelog.

---------

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
Diffstat (limited to 'lib')
-rw-r--r--lib/pure/collections/sequtils.nim9
1 files changed, 9 insertions, 0 deletions
diff --git a/lib/pure/collections/sequtils.nim b/lib/pure/collections/sequtils.nim
index bcdd0879d..19bc3e65c 100644
--- a/lib/pure/collections/sequtils.nim
+++ b/lib/pure/collections/sequtils.nim
@@ -248,6 +248,15 @@ func maxIndex*[T](s: openArray[T]): int {.since: (1, 1).} =
   for i in 1..high(s):
     if s[i] > s[result]: result = i
 
+func minmax*[T](x: openArray[T]): (T, T) =
+  ## The minimum and maximum values of `x`. `T` needs to have a `<` operator.
+  var l = x[0]
+  var h = x[0]
+  for i in 1..high(x):
+    if x[i] < l: l = x[i]
+    if h < x[i]: h = x[i]
+  result = (l, h)
+
 
 template zipImpl(s1, s2, retType: untyped): untyped =
   proc zip*[S, T](s1: openArray[S], s2: openArray[T]): retType =