From de9ba502b99e203485fdef516e0608e007c3aaee Mon Sep 17 00:00:00 2001 From: Karsten Schmidt Date: Thu, 5 Oct 2023 13:06:24 +0200 Subject: [PATCH] feat(arrays): add selectThresholdMin/Max() fns --- packages/arrays/src/threshold.ts | 57 ++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 packages/arrays/src/threshold.ts diff --git a/packages/arrays/src/threshold.ts b/packages/arrays/src/threshold.ts new file mode 100644 index 0000000000..bdba53375c --- /dev/null +++ b/packages/arrays/src/threshold.ts @@ -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 = ( + thresholds: Record, + 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 = ( + thresholds: Record, + 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; + }; +};