1 """Percentage util functions."""
3 from __future__
import annotations
7 scale_ranged_value_to_int_range,
13 def ordered_list_item_to_percentage[_T](ordered_list: list[_T], item: _T) -> int:
14 """Determine the percentage of an item in an ordered list.
16 When using this utility for fan speeds, do not include "off"
18 Given the list: ["low", "medium", "high", "very_high"], this
19 function will return the following when the item is passed
28 if item
not in ordered_list:
29 raise ValueError(f
'The item "{item}" is not in "{ordered_list}"')
31 list_len = len(ordered_list)
32 list_position = ordered_list.index(item) + 1
33 return (list_position * 100) // list_len
36 def percentage_to_ordered_list_item[_T](ordered_list: list[_T], percentage: int) -> _T:
37 """Find the item that most closely matches the percentage in an ordered list.
39 When using this utility for fan speeds, do not include "off"
41 Given the list: ["low", "medium", "high", "very_high"], this
42 function will return the following when when the item is passed
50 if not (list_len := len(ordered_list)):
51 raise ValueError(
"The ordered list is empty")
53 for offset, speed
in enumerate(ordered_list):
54 list_position = offset + 1
55 upper_bound = (list_position * 100) // list_len
56 if percentage <= upper_bound:
59 return ordered_list[-1]
63 low_high_range: tuple[float, float], value: float
65 """Given a range of low and high values convert a single value to a percentage.
67 When using this utility for fan speeds, do not include 0 if it is off
69 Given a low value of 1 and a high value of 255 this function
80 low_high_range: tuple[float, float], percentage: float
82 """Given a range of low and high values convert a percentage to a single value.
84 When using this utility for fan speeds, do not include 0 if it is off
86 Given a low value of 1 and a high value of 255 this function
float percentage_to_ranged_value(tuple[float, float] low_high_range, float percentage)
int ranged_value_to_percentage(tuple[float, float] low_high_range, float value)
int scale_ranged_value_to_int_range(tuple[float, float] source_low_high_range, tuple[float, float] target_low_high_range, float value)
float scale_to_ranged_value(tuple[float, float] source_low_high_range, tuple[float, float] target_low_high_range, float value)