-
-
Notifications
You must be signed in to change notification settings - Fork 144
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(arrays): add selectThresholdMin/Max() fns
- Loading branch information
1 parent
33512ec
commit de9ba50
Showing
1 changed file
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
/** | ||
* Higher order function. Takes an object of threshold values and their target | ||
* values, as well as a default value. Returns a new function which then matches | ||
* a given value against all given thresholds and returns a matching target | ||
* value, of (if none matched), the given default. | ||
* | ||
* @remarks | ||
* The thresholds will be sorted & matched in ascending order using `<=` | ||
* comparison. | ||
* | ||
* @example | ||
* ```ts | ||
* const numColumns = selectThresholdMin({ 480: 1, 640: 2, 960: 3 }, 4); | ||
* | ||
* numColumns(320) // 1 | ||
* | ||
* numColumns(481) // 2 | ||
* | ||
* numColumns(768) // 3 | ||
* | ||
* numColumns(1024) // 4 | ||
* ``` | ||
* | ||
* @param thresholds | ||
* @param defaultVal | ||
*/ | ||
export const selectThresholdMin = <T>( | ||
thresholds: Record<number, T>, | ||
defaultVal: T | ||
) => { | ||
const $thresholds = Object.entries(thresholds) | ||
.map(([k, v]) => <[number, T]>[+k, v]) | ||
.sort((a, b) => a[0] - b[0]); | ||
return (x: number) => { | ||
const res = $thresholds.find((t) => x <= t[0]); | ||
return res ? res[1] : defaultVal; | ||
}; | ||
}; | ||
|
||
/** | ||
* Similar to {@link selectThresholdMin}, but uses `>=` ordering. | ||
* | ||
* @param thresholds | ||
* @param defaultVal | ||
*/ | ||
export const selectThresholdMax = <T>( | ||
thresholds: Record<number, T>, | ||
defaultVal: T | ||
) => { | ||
const $thresholds = Object.entries(thresholds) | ||
.map(([k, v]) => <[number, T]>[+k, v]) | ||
.sort((a, b) => b[0] - a[0]); | ||
return (x: number) => { | ||
const res = $thresholds.find((t) => x >= t[0]); | ||
return res ? res[1] : defaultVal; | ||
}; | ||
}; |