|
| 1 | +import { CategoryValueKey, SelectedFilter } from "../../../entities"; |
| 2 | +import { isSelectedRange } from "./typeGuards"; |
| 3 | +import { SelectedRange } from "./types"; |
| 4 | + |
| 5 | +/** |
| 6 | + * Asserts that the given value is a selected range. |
| 7 | + * Throws an error if the value is not a selected range. |
| 8 | + * @param value - Value to assert is a selected range. |
| 9 | + */ |
| 10 | +export function assertIsRange(value: unknown): asserts value is SelectedRange { |
| 11 | + if (!isSelectedRange(value)) { |
| 12 | + throw new Error("Value is not SelectedRange"); |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +/** |
| 17 | + * Build the next filter state for the given range category. |
| 18 | + * @param nextCategorySelectedFilter - Next filter state for the range category. |
| 19 | + * @param selectedValue - Selected value for the range category. |
| 20 | + * @param selected - Whether the category value is selected. |
| 21 | + */ |
| 22 | +export function buildNextRangeFilterState( |
| 23 | + nextCategorySelectedFilter: SelectedFilter, |
| 24 | + selectedValue: CategoryValueKey, |
| 25 | + selected: boolean |
| 26 | +): void { |
| 27 | + if (selected) { |
| 28 | + // Assert that the selected value is a range. |
| 29 | + assertIsRange(selectedValue); |
| 30 | + // Set the selected range. |
| 31 | + nextCategorySelectedFilter.value = selectedValue; |
| 32 | + } else { |
| 33 | + // Remove the selected range. |
| 34 | + nextCategorySelectedFilter.value = []; |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +/** |
| 39 | + * Get the selected values for the given category, if any. |
| 40 | + * Handles type checking for selected range. |
| 41 | + * Falls back to empty array if no selected values or invalid type (should never happen). |
| 42 | + * @param categorySelectedFilter - Current filter state for a category. |
| 43 | + * @returns The selected filter (i.e. the set of selected values) for the given category. |
| 44 | + */ |
| 45 | +export function getRangeSelectedValue( |
| 46 | + categorySelectedFilter?: SelectedFilter |
| 47 | +): SelectedRange { |
| 48 | + return isSelectedRange(categorySelectedFilter?.value) |
| 49 | + ? categorySelectedFilter?.value |
| 50 | + : [null, null]; |
| 51 | +} |
0 commit comments