diff --git a/packages/lib/package.json b/packages/lib/package.json index 6456741..11ea0ad 100644 --- a/packages/lib/package.json +++ b/packages/lib/package.json @@ -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" } -} +} \ No newline at end of file diff --git a/packages/lib/src/Tools.ts b/packages/lib/src/Tools.ts index 3a7867c..465b21f 100644 --- a/packages/lib/src/Tools.ts +++ b/packages/lib/src/Tools.ts @@ -413,6 +413,15 @@ export const toggle = (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 = (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: 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