Merge pull request #16 from ticruz38/feat/hurdak

Add 2 missing functions from hurdak
This commit is contained in:
hodlbod
2025-01-24 09:02:45 -08:00
committed by GitHub
2 changed files with 29 additions and 2 deletions
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@welshman/lib",
"version": "0.0.37",
"version": "0.0.38",
"author": "hodlbod",
"license": "MIT",
"description": "A collection of utilities.",
@@ -30,4 +30,4 @@
"@types/events": "^3.0.3",
"events": "^3.3.0"
}
}
}
+27
View File
@@ -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 = <T extends Record<string, any>>(f: (v: any) => boolean, x: T) => {
const r = {} as T
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