Added math.clamp for slice clamping (#17246)

* Added math.clamp for slice clamping

* Added inline to math.clamp

* Cleaned up math.clamp + test
This commit is contained in:
Jason Beetham 2021-03-03 16:54:23 -07:00 • committed by GitHub
commit c180de60a8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 23 additions and 0 deletions

View file

@ -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`.
##