summaryrefslogtreecommitdiff
path: root/apps/web/src/utils/math.ts
blob: ac82ca17b3444e61a7381d524af9477003d314db (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
export function clamp({
	value,
	min,
	max,
}: {
	value: number;
	min: number;
	max: number;
}): number {
	return Math.max(min, Math.min(max, value));
}

export function evaluateMathExpression({
	input,
}: {
	input: string;
}): number | null {
	const sanitized = input.trim();
	if (!/^[\d.\s+\-*/()]+$/.test(sanitized)) return null;
	try {
		const result = new Function(`return (${sanitized})`)();
		if (typeof result !== "number" || !Number.isFinite(result)) return null;
		return result;
	} catch {
		return null;
	}
}