mirror of
https://github.com/Textualize/textual.git
synced 2025-10-17 02:38:12 +03:00
clamp micro-optimization
This commit is contained in:
@@ -33,8 +33,13 @@ T = TypeVar("T", int, float)
|
||||
|
||||
|
||||
def clamp(value: T, minimum: T, maximum: T) -> T:
|
||||
"""Adjust a value so it is not less than a minimum and not greater
|
||||
than a maximum value.
|
||||
"""Restrict a value to a given range.
|
||||
|
||||
If `value` is less than the minimum, return the minimum.
|
||||
If `value` is greater than the maximum, return the maximum.
|
||||
Otherwise, return `value`.
|
||||
|
||||
The `minimum` and `maximum` arguments values may be given in reverse order.
|
||||
|
||||
Args:
|
||||
value: A value.
|
||||
@@ -45,12 +50,18 @@ def clamp(value: T, minimum: T, maximum: T) -> T:
|
||||
New value that is not less than the minimum or greater than the maximum.
|
||||
"""
|
||||
if minimum > maximum:
|
||||
maximum, minimum = minimum, maximum
|
||||
if value < minimum:
|
||||
return minimum
|
||||
elif value > maximum:
|
||||
return maximum
|
||||
# It is common for the min and max to be in non-intuitive order.
|
||||
# Rather than force the caller to get it right, it is simpler to handle it here.
|
||||
if value < maximum:
|
||||
return maximum
|
||||
if value > minimum:
|
||||
return minimum
|
||||
return value
|
||||
else:
|
||||
if value < minimum:
|
||||
return minimum
|
||||
if value > maximum:
|
||||
return maximum
|
||||
return value
|
||||
|
||||
|
||||
|
||||
@@ -62,6 +62,14 @@ def test_clamp():
|
||||
assert clamp(10, 0, 10) == 10
|
||||
assert clamp(5, 10, 0) == 5
|
||||
|
||||
# range in reverse order
|
||||
assert clamp(5, 10, 0) == 5
|
||||
assert clamp(-1, 10, 0) == 0
|
||||
assert clamp(11, 10, 0) == 10
|
||||
assert clamp(0, 10, 0) == 0
|
||||
assert clamp(10, 10, 0) == 10
|
||||
assert clamp(5, 0, 10) == 5
|
||||
|
||||
|
||||
def test_offset_bool():
|
||||
assert Offset(1, 0)
|
||||
|
||||
Reference in New Issue
Block a user