From bafefa8156a15e74ad6d575b678fb55c4f0fea06 Mon Sep 17 00:00:00 2001 From: beam Date: Mon, 26 Oct 2026 20:46:33 +0000 Subject: [PATCH] beam: add clamp primitive with tests --- wizard-work/beam/clamp.py | 12 ++++++++++++ wizard-work/beam/test_clamp.py | 20 ++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 wizard-work/beam/clamp.py create mode 100644 wizard-work/beam/test_clamp.py diff --git a/wizard-work/beam/clamp.py b/wizard-work/beam/clamp.py new file mode 100644 index 0000000..801a8e2 --- /dev/null +++ b/wizard-work/beam/clamp.py @@ -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 diff --git a/wizard-work/beam/test_clamp.py b/wizard-work/beam/test_clamp.py new file mode 100644 index 0000000..c8a0c6a --- /dev/null +++ b/wizard-work/beam/test_clamp.py @@ -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()