beam: add clamp primitive with tests

This commit is contained in:
beam committed 2026-10-26 20:46:33 +00:00
1 parent d693f682ff
commit bafefa8156
2 files changed
+32

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
"""Clamp a value to [lo, hi]. Handles None by raising, preserves type."""
from __future__ import annotations
def clamp(value, lo, hi):
if lo > hi:
raise ValueError("lo > hi: %r > %r" % (lo, hi))
if value < lo:
return lo
if value > hi:
return hi
return value
+20
View File
@@ -0,0 +1,20 @@
import unittest
from clamp import clamp
class TestClamp(unittest.TestCase):
def test_basic(self):
self.assertEqual(clamp(5, 0, 10), 5)
self.assertEqual(clamp(-3, 0, 10), 0)
self.assertEqual(clamp(15, 0, 10), 10)
def test_bounds_equal(self):
self.assertEqual(clamp(5, 7, 7), 7)
def test_lo_gt_hi_raises(self):
with self.assertRaises(ValueError):
clamp(5, 10, 0)
def test_floats(self):
self.assertEqual(clamp(1.5, 0.0, 1.0), 1.0)
if __name__ == "__main__":
unittest.main()