summary refs log tree commit diff stats
path: root/lib/pure/math.nim
diff options
context:
space:
mode:
Diffstat (limited to 'lib/pure/math.nim')
-rw-r--r--lib/pure/math.nim10
1 files changed, 10 insertions, 0 deletions
diff --git a/lib/pure/math.nim b/lib/pure/math.nim
index 9e48ecf5d..95c57730f 100644
--- a/lib/pure/math.nim
+++ b/lib/pure/math.nim
@@ -1182,6 +1182,16 @@ func lcm*[T](x, y: T): T =
 
   x div gcd(x, y) * y
 
+func clamp*[T](val: T, bounds: Slice[T]): T {.since: (1, 5), inline.} =
+  ## Like `system.clamp`, but takes a slice, so you can easily clamp within a range.
+  runnableExamples:
+    assert clamp(10, 1 .. 5) == 5
+    assert clamp(1, 1 .. 3) == 1
+    type A = enum a0, a1, a2, a3, a4, a5
+    assert a1.clamp(a2..a4) == a2
+    assert clamp((3, 0), (1, 0) .. (2, 9)) == (2, 9)
+  clamp(val, bounds.a, bounds.b)
+
 func lcm*[T](x: openArray[T]): T {.since: (1, 1).} =
   ## Computes the least common multiple of the elements of `x`.
   ##