add round and filterVals functions from hurdak
This commit is contained in:
@@ -413,6 +413,15 @@ export const toggle = <T>(x: T, xs: T[]) => (xs.includes(x) ? remove(x, xs) : ap
|
||||
*/
|
||||
export const clamp = ([min, max]: [number, number], n: number) => Math.min(max, Math.max(min, n))
|
||||
|
||||
/**
|
||||
* Round a number to the nearest float precision
|
||||
* @param precision - Number of decimal places
|
||||
* @param x - Number to round
|
||||
* @returns Formatted number
|
||||
*/
|
||||
export const round = (precision: number, x: number) =>
|
||||
Math.round(x * Math.pow(10, precision)) / Math.pow(10, precision)
|
||||
|
||||
/**
|
||||
* Safely parses JSON string
|
||||
* @param json - JSON string to parse
|
||||
@@ -663,6 +672,24 @@ export const fromPairs = <T>(pairs: [k?: string, v?: T, ...args: unknown[]][]) =
|
||||
return r
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters object values based on predicate
|
||||
* @param f - Function to test values
|
||||
* @param x - Object to filter
|
||||
* @returns Object with only values that pass predicate
|
||||
*/
|
||||
export const filterVals = (f: (v: any) => boolean, x: Record<string, any>) => {
|
||||
const r = {} as Record<string, any>
|
||||
|
||||
for (const k in x) {
|
||||
if (f(x[k])) {
|
||||
r[k] = x[k]
|
||||
}
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
/**
|
||||
* Flattens array of arrays into single array
|
||||
* @param xs - Array of arrays to flatten
|
||||
|
||||
Reference in New Issue
Block a user