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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
|
export function clamp({
value,
min,
max,
}: {
value: number;
min: number;
max: number;
}): number {
return Math.max(min, Math.min(max, value));
}
export function clampRound({
value,
min,
max,
}: {
value: number;
min: number;
max: number;
}): number {
return Math.round(clamp({ value, min, max }));
}
export function getFractionDigitsForStep({ step }: { step: number }): number {
const normalizedStep = step.toString().toLowerCase();
if (normalizedStep.includes("e-")) {
return Number(normalizedStep.split("e-")[1] ?? 0);
}
const [, fractionalPart = ""] = normalizedStep.split(".");
return fractionalPart.length;
}
export function snapToStep({
value,
step,
}: {
value: number;
step: number;
}): number {
if (step <= 0) return value;
const snappedValue = Math.round(value / step) * step;
return Number(
snappedValue.toFixed(getFractionDigitsForStep({ step })),
);
}
export function isNearlyEqual({
leftValue,
rightValue,
epsilon = 0.0001,
}: {
leftValue: number;
rightValue: number;
epsilon?: number;
}): boolean {
return Math.abs(leftValue - rightValue) <= epsilon;
}
export function formatNumberForDisplay({
value,
fractionDigits,
minFractionDigits = 0,
maxFractionDigits = 6,
}: {
value: number;
fractionDigits?: number;
minFractionDigits?: number;
maxFractionDigits?: number;
}): string {
const resolvedMaxFractionDigits = Math.max(
0,
fractionDigits ?? maxFractionDigits,
);
const resolvedMinFractionDigits = Math.min(
Math.max(0, fractionDigits ?? minFractionDigits),
resolvedMaxFractionDigits,
);
const fixedValue = value.toFixed(resolvedMaxFractionDigits);
if (resolvedMaxFractionDigits === 0) {
return Number(fixedValue) === 0 ? "0" : fixedValue;
}
const [integerPart, fractionPart = ""] = fixedValue.split(".");
const normalizedIntegerPart = Number(fixedValue) === 0 ? "0" : integerPart;
let trimmedFractionPart = fractionPart;
while (
trimmedFractionPart.length > resolvedMinFractionDigits &&
trimmedFractionPart.endsWith("0")
) {
trimmedFractionPart = trimmedFractionPart.slice(0, -1);
}
return trimmedFractionPart
? `${normalizedIntegerPart}.${trimmedFractionPart}`
: normalizedIntegerPart;
}
/**
* Safely evaluates a mathematical expression without using eval() or new Function().
* Supports +, -, *, /, parentheses, and decimal numbers.
*/
export function evaluateMathExpression({
input,
}: {
input: string;
}): number | null {
const sanitized = input.trim();
if (!/^[\d.\s+\-*/()]+$/.test(sanitized)) return null;
try {
return parseExpression(sanitized);
} catch {
return null;
}
}
/**
* Recursive descent parser for basic arithmetic expressions.
* Grammar:
* expression = term { ('+' | '-') term }
* term = factor { ('*' | '/') factor }
* factor = number | '(' expression ')'
*/
function parseExpression(input: string): number | null {
const tokens = tokenize(input);
if (tokens.length === 0) return null;
let index = 0;
function peek(): Token | null {
return tokens[index] ?? null;
}
function consume(): Token | null {
return tokens[index++] ?? null;
}
function parseExpressionLevel(): number {
let left = parseTerm();
while (true) {
const token = peek();
if (token?.type === "PLUS") {
consume();
left = left + parseTerm();
} else if (token?.type === "MINUS") {
consume();
left = left - parseTerm();
} else {
break;
}
}
return left;
}
function parseTerm(): number {
let left = parseFactor();
while (true) {
const token = peek();
if (token?.type === "MULTIPLY") {
consume();
left = left * parseFactor();
} else if (token?.type === "DIVIDE") {
consume();
const right = parseFactor();
if (right === 0) throw new Error("Division by zero");
left = left / right;
} else {
break;
}
}
return left;
}
function parseFactor(): number {
const token = peek();
if (!token) throw new Error("Unexpected end of expression");
if (token.type === "NUMBER") {
consume();
return token.value;
}
if (token.type === "MINUS") {
consume();
return -parseFactor();
}
if (token.type === "LPAREN") {
consume();
const value = parseExpressionLevel();
const next = peek();
if (next?.type !== "RPAREN") {
throw new Error("Missing closing parenthesis");
}
consume();
return value;
}
throw new Error(`Unexpected token: ${token.type}`);
}
const result = parseExpressionLevel();
if (index !== tokens.length) {
return null;
}
if (!Number.isFinite(result)) return null;
return result;
}
type Token =
| { type: "NUMBER"; value: number }
| { type: "PLUS" }
| { type: "MINUS" }
| { type: "MULTIPLY" }
| { type: "DIVIDE" }
| { type: "LPAREN" }
| { type: "RPAREN" };
function tokenize(input: string): Token[] {
const tokens: Token[] = [];
let i = 0;
const str = input.trim();
while (i < str.length) {
const char = str[i];
if (/\s/.test(char)) {
i++;
continue;
}
if (/\d/.test(char)) {
let numStr = "";
while (i < str.length && (/\d/.test(str[i]) || str[i] === ".")) {
numStr += str[i];
i++;
}
const value = Number(numStr);
if (!Number.isFinite(value)) {
throw new Error(`Invalid number: ${numStr}`);
}
tokens.push({ type: "NUMBER", value });
continue;
}
switch (char) {
case "+":
tokens.push({ type: "PLUS" });
break;
case "-":
tokens.push({ type: "MINUS" });
break;
case "*":
tokens.push({ type: "MULTIPLY" });
break;
case "/":
tokens.push({ type: "DIVIDE" });
break;
case "(":
tokens.push({ type: "LPAREN" });
break;
case ")":
tokens.push({ type: "RPAREN" });
break;
default:
throw new Error(`Invalid character: ${char}`);
}
i++;
}
return tokens;
}
|