From e45b15ffb7c4a97867de182864ca743f8721884a Mon Sep 17 00:00:00 2001 From: Jon Staab Date: Thu, 14 Nov 2024 13:13:41 -0800 Subject: [PATCH] Make math utils more tolerant of nil --- packages/lib/src/Tools.ts | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/packages/lib/src/Tools.ts b/packages/lib/src/Tools.ts index 0dcc3e7..cce3934 100644 --- a/packages/lib/src/Tools.ts +++ b/packages/lib/src/Tools.ts @@ -25,33 +25,35 @@ export const identity = (x: T, ...args: unknown[]) => x export const always = (x: T, ...args: unknown[]) => () => x -export const add = (x: number | Nil, y: number | Nil) => (x || 0) + (y || 0) +export const num = (x: Maybe) => x || 0 -export const sub = (x: number | Nil, y: number | Nil) => (x || 0) - (y || 0) +export const add = (x: Maybe, y: Maybe) => num(x) + num(y) -export const mul = (x: number | Nil, y: number | Nil) => (x || 0) * (y || 0) +export const sub = (x: Maybe, y: Maybe) => num(x) - num(y) -export const div = (x: number | Nil, y: number) => (x || 0) / y +export const mul = (x: Maybe, y: Maybe) => num(x) * num(y) -export const inc = (x: number | Nil) => add(x, 1) +export const div = (x: Maybe, y: number) => num(x) / y -export const dec = (x: number | Nil) => sub(x, 1) +export const inc = (x: Maybe) => add(x, 1) -export const lt = (x: number | Nil, y: number | Nil) => (x || 0) < (y || 0) +export const dec = (x: Maybe) => sub(x, 1) -export const lte = (x: number | Nil, y: number | Nil) => (x || 0) <= (y || 0) +export const lt = (x: Maybe, y: Maybe) => num(x) < num(y) -export const gt = (x: number | Nil, y: number | Nil) => (x || 0) > (y || 0) +export const lte = (x: Maybe, y: Maybe) => num(x) <= num(y) -export const gte = (x: number | Nil, y: number | Nil) => (x || 0) >= (y || 0) +export const gt = (x: Maybe, y: Maybe) => num(x) > num(y) -export const max = (xs: number[]) => xs.reduce((a, b) => Math.max(a, b), 0) +export const gte = (x: Maybe, y: Maybe) => num(x) >= num(y) -export const min = (xs: number[]) => xs.reduce((a, b) => Math.min(a, b), 0) +export const max = (xs: Maybe[]) => xs.reduce((a: number, b) => Math.max(num(a), num(b)), 0) -export const sum = (xs: number[]) => xs.reduce((a, b) => a + b, 0) +export const min = (xs: Maybe[]) => xs.reduce((a: number, b) => Math.min(num(a), num(b)), 0) -export const avg = (xs: number[]) => sum(xs) / xs.length +export const sum = (xs: Maybe[]) => xs.reduce((a: number, b) => add(a, b), 0) + +export const avg = (xs: Maybe[]) => sum(xs) / xs.length export const drop = (n: number, xs: T[]) => xs.slice(n)