exprify 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.gitattributes +2 -0
- package/.github/workflows/ci.yml +40 -0
- package/.github/workflows/npm-publish.yml +38 -0
- package/.github/workflows/security-audit.yml +34 -0
- package/CHANGELOG.md +11 -0
- package/LICENSE +673 -673
- package/README.md +203 -135
- package/dist/exprify.cjs.js +2320 -503
- package/dist/exprify.cjs.js.map +1 -1
- package/dist/exprify.esm.js +2320 -497
- package/dist/exprify.esm.js.map +1 -1
- package/dist/exprify.js +2340 -523
- package/dist/exprify.js.map +1 -1
- package/dist/exprify.min.js +2 -2
- package/dist/exprify.min.js.map +1 -1
- package/doc/tokenType.txt +48 -0
- package/package.json +7 -3
- package/rollup.config.js +80 -0
- package/src/assets/capture.jpg +0 -0
- package/src/core/Exprify.js +140 -70
- package/src/core/context.js +30 -0
- package/src/function/executor.js +64 -0
- package/src/function/internal.js +270 -0
- package/src/function/registry.js +68 -0
- package/src/index.js +2 -38
- package/src/math/operations.js +37 -47
- package/src/parser/astBuild.js +508 -0
- package/src/parser/evaluator.js +430 -57
- package/src/parser/tokenizer.js +399 -145
- package/src/utils/globalUnits.js +217 -0
- package/src/utils/store.js +178 -0
- package/src/variables/store.js +75 -0
- package/test/browser.html +23 -0
- package/test/exprify.test.js +140 -0
- package/src/functions/externalFunctions.js +0 -19
- package/src/functions/internalFunctions.js +0 -53
- package/src/parser/infixToPostfix.js +0 -78
- package/src/utils/typeConverter.js +0 -63
- package/src/variables/variables.js +0 -28
package/dist/exprify.esm.js
CHANGED
|
@@ -1,511 +1,2334 @@
|
|
|
1
|
-
function tokenize(expr, context) {
|
|
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
|
-
|
|
1
|
+
function tokenize(expr, context = {}) {
|
|
2
|
+
const tokens = [];
|
|
3
|
+
let current = "";
|
|
4
|
+
let quote = "";
|
|
5
|
+
|
|
6
|
+
const operators = ["+", "-", "*", "/", "%", "^", "=", ">", "<", "!", "&", "|"];
|
|
7
|
+
const multiOps = [
|
|
8
|
+
"==", ">=", "<=", "&&", "||",
|
|
9
|
+
"+=", "-=", "*=", "/=", "%=",
|
|
10
|
+
"?.", "??", "|>"
|
|
11
|
+
];
|
|
12
|
+
|
|
13
|
+
const parentheses = "()";
|
|
14
|
+
const comma = ",";
|
|
15
|
+
const semicolon = ";";
|
|
16
|
+
const keywords = ["to", "in"];
|
|
17
|
+
// const functions = context.functions?.getAllFunctionsName?.() || [];
|
|
18
|
+
const units = context.units?.getAllUnitsFlat?.() || [];
|
|
19
|
+
|
|
20
|
+
const isIdentifier = (s) => /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s);
|
|
21
|
+
|
|
22
|
+
function getContext(str, charIndex) {
|
|
23
|
+
// 1. Extract all alphanumeric words into an array
|
|
24
|
+
const words = str.match(/[a-z0-9]+/gi) || [];
|
|
25
|
+
|
|
26
|
+
// 2. Identify the current character and the one immediately before it
|
|
27
|
+
const currentChar = str[charIndex] || null;
|
|
28
|
+
const prevChar = charIndex > 0 ? str[charIndex - 1] : null;
|
|
29
|
+
|
|
30
|
+
// 3. Find the word that contains the current charIndex
|
|
31
|
+
let start = charIndex;
|
|
32
|
+
// Move pointer back to the start of the current word
|
|
33
|
+
while (start > 0 && /[a-z0-9]/i.test(str[start - 1])) start--;
|
|
34
|
+
|
|
35
|
+
let end = charIndex;
|
|
36
|
+
// Move pointer forward to the end of the current word
|
|
37
|
+
while (end < str.length && /[a-z0-9]/i.test(str[end])) end++;
|
|
38
|
+
|
|
39
|
+
const currentWord = str.substring(start, end);
|
|
40
|
+
|
|
41
|
+
// 4. Find the word that appears before the currentWord in the sequence
|
|
42
|
+
const currentWordIdx = words.indexOf(currentWord);
|
|
43
|
+
const prevWord = currentWordIdx > 0 ? words[currentWordIdx - 1] : null;
|
|
44
|
+
|
|
45
|
+
// 5. Find the word that appears after the currentWord
|
|
46
|
+
const nextWord = (currentWordIdx !== -1 && currentWordIdx < words.length - 1)
|
|
47
|
+
? words[currentWordIdx + 1]
|
|
48
|
+
: null;
|
|
49
|
+
|
|
50
|
+
return {
|
|
51
|
+
prevWord: prevWord,
|
|
52
|
+
prevChar: prevChar,
|
|
53
|
+
currentWord: currentWord,
|
|
54
|
+
currentChar: currentChar,
|
|
55
|
+
nextWord: nextWord
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const isUnaryContext = (prev) =>
|
|
60
|
+
!prev ||
|
|
61
|
+
prev.type === "Operator" ||
|
|
62
|
+
prev.type === "UnaryOperator" ||
|
|
63
|
+
(prev.type === "Parenthesis" && prev.value !== ")") ||
|
|
64
|
+
prev.type === "ArrayStart" ||
|
|
65
|
+
prev.type === "Semicolon" ||
|
|
66
|
+
prev.type === "Comma" ||
|
|
67
|
+
prev.type === "Ternary";
|
|
68
|
+
|
|
69
|
+
const flushCurrent = (nextChar, index) => {
|
|
70
|
+
if (!current) return;
|
|
71
|
+
|
|
72
|
+
// BOOLEAN
|
|
73
|
+
if (/^(true|false)$/i.test(current)) {
|
|
74
|
+
tokens.push({ type: "Boolean", value: current.toLowerCase() === "true" });
|
|
75
|
+
current = "";
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// KEYWORD
|
|
80
|
+
if (keywords.includes(current)) {
|
|
81
|
+
tokens.push({ type: "Keyword", value: current, pos: index });
|
|
82
|
+
current = "";
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// BIGINT
|
|
87
|
+
if (/^\d+n$/.test(current)) {
|
|
88
|
+
tokens.push({ type: "BigInt", value: BigInt(current.slice(0, -1)), pos: index });
|
|
89
|
+
current = "";
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// HEX
|
|
94
|
+
if (/^0x[0-9a-fA-F]+$/.test(current)) {
|
|
95
|
+
tokens.push({ type: "Number", value: parseInt(current, 16), pos: index });
|
|
96
|
+
current = "";
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// BINARY
|
|
101
|
+
if (/^0b[01]+$/.test(current)) {
|
|
102
|
+
tokens.push({ type: "Number", value: parseInt(current, 2), pos: index });
|
|
103
|
+
current = "";
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// NUMBER (including scientific)
|
|
108
|
+
if (/^[+-]?(\d+(\.\d+)?|\.\d+)(e[+-]?\d+)?$/i.test(current)) {
|
|
109
|
+
tokens.push({ type: "Number", value: parseFloat(current), pos: index });
|
|
110
|
+
current = "";
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// IMAGINARY NUMBER
|
|
115
|
+
if (/^[+-]?(\d+(\.\d+)?|\.\d+)(e[+-]?\d+)?i$/i.test(current)) {
|
|
116
|
+
tokens.push({
|
|
117
|
+
type: "ImaginaryLiteral",
|
|
118
|
+
value: parseFloat(current.slice(0, -1)),
|
|
119
|
+
pos: index
|
|
120
|
+
});
|
|
121
|
+
current = "";
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// IMAGINARY UNIT
|
|
126
|
+
if (/^[+-]?i$/i.test(current)) {
|
|
127
|
+
const sign = current[0] === "-" ? -1 : 1;
|
|
128
|
+
tokens.push({
|
|
129
|
+
type: "ImaginaryLiteral",
|
|
130
|
+
value: sign,
|
|
131
|
+
pos: index
|
|
132
|
+
});
|
|
133
|
+
current = "";
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// NUMBER + UNIT
|
|
138
|
+
const numUnit = current.match(/^([+-]?\d+(\.\d+)?)([a-zA-Z]+)$/);
|
|
139
|
+
if (numUnit) {
|
|
140
|
+
const value = parseFloat(numUnit[1]);
|
|
141
|
+
const unit = numUnit[3];
|
|
142
|
+
|
|
143
|
+
tokens.push({
|
|
144
|
+
type: units.includes(unit) ? "NumberWithUnit" : "UnknownUnit",
|
|
145
|
+
value,
|
|
146
|
+
unit,
|
|
147
|
+
pos: index
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
current = "";
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// UNIT
|
|
155
|
+
if (units.includes(current)) {
|
|
156
|
+
const {prevWord} = getContext(expr, index);
|
|
157
|
+
if (nextChar !== "(") {
|
|
158
|
+
if (prevWord){
|
|
159
|
+
if (!isNaN(parseFloat(prevWord)) || prevWord === "to" || prevWord === "in") {
|
|
160
|
+
// console.log("Context for unit detection:", {current, prevWord, nextChar});
|
|
161
|
+
|
|
162
|
+
tokens.push({ type: "Unit", value: current, pos: index });
|
|
163
|
+
current = "";
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// IDENTIFIER
|
|
171
|
+
if (isIdentifier(current)) {
|
|
172
|
+
if (nextChar === "(") {
|
|
173
|
+
tokens.push({
|
|
174
|
+
type: "Function",
|
|
175
|
+
name: current,
|
|
176
|
+
pos: index
|
|
177
|
+
});
|
|
178
|
+
} else {
|
|
179
|
+
tokens.push({
|
|
180
|
+
type: "Identifier",
|
|
181
|
+
name: current,
|
|
182
|
+
pos: index
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
current = "";
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
throw new Error(`Invalid token "${current}" at index ${index}`);
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
for (let i = 0; i < expr.length; i++) {
|
|
195
|
+
let char = expr[i];
|
|
196
|
+
let next = expr[i + 1];
|
|
197
|
+
|
|
198
|
+
// comments
|
|
199
|
+
if (char === "/" && next === "/") {
|
|
200
|
+
while (i < expr.length && expr[i] !== "\n") i++;
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
if (char === "/" && next === "*") {
|
|
205
|
+
i += 2;
|
|
206
|
+
while (i < expr.length && !(expr[i] === "*" && expr[i + 1] === "/")) i++;
|
|
207
|
+
i++;
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// string
|
|
212
|
+
if (`"'`.includes(char)) {
|
|
213
|
+
if (!quote) {
|
|
214
|
+
quote = char;
|
|
215
|
+
current += char;
|
|
216
|
+
} else if (quote === char) {
|
|
217
|
+
current += char;
|
|
218
|
+
tokens.push({
|
|
219
|
+
type: "String",
|
|
220
|
+
value: current.slice(1, -1),
|
|
221
|
+
pos: i
|
|
222
|
+
});
|
|
223
|
+
current = "";
|
|
224
|
+
quote = "";
|
|
225
|
+
} else {
|
|
226
|
+
current += char;
|
|
227
|
+
}
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if (quote) {
|
|
232
|
+
if (char === "\\") {
|
|
233
|
+
current += char + expr[++i];
|
|
234
|
+
} else {
|
|
235
|
+
current += char;
|
|
236
|
+
}
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// multi operators
|
|
241
|
+
const twoChar = char + next;
|
|
242
|
+
if (multiOps.includes(twoChar)) {
|
|
243
|
+
flushCurrent(char, i);
|
|
244
|
+
tokens.push({ type: "Operator", value: twoChar, pos: i });
|
|
245
|
+
i++;
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
if (char === "?") {
|
|
250
|
+
tokens.push({ type: "Ternary", value: "?" });
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// only treat ':' as ternary IF previous token was '?'
|
|
255
|
+
if (char === ":") {
|
|
256
|
+
flushCurrent(char, i);
|
|
257
|
+
const prev = tokens[tokens.length - 1];
|
|
258
|
+
|
|
259
|
+
if (prev && prev.type === "Ternary") {
|
|
260
|
+
tokens.push({ type: "Ternary", value: ":" });
|
|
261
|
+
} else {
|
|
262
|
+
tokens.push({ type: "Colon" });
|
|
263
|
+
}
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// dot
|
|
268
|
+
if (char === "." && /\d/.test(current) && /\d/.test(next)) {
|
|
269
|
+
current += char;
|
|
270
|
+
continue;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
if (char === ".") {
|
|
274
|
+
flushCurrent(char, i);
|
|
275
|
+
tokens.push({ type: "Dot", pos: i });
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// operators
|
|
280
|
+
if (operators.includes(char)) {
|
|
281
|
+
flushCurrent(char, i);
|
|
282
|
+
|
|
283
|
+
const prev = tokens[tokens.length - 1];
|
|
284
|
+
if ((char === "-" || char === "!") && isUnaryContext(prev)) {
|
|
285
|
+
tokens.push({ type: "UnaryOperator", value: char, pos: i });
|
|
286
|
+
} else {
|
|
287
|
+
tokens.push({ type: "Operator", value: char, pos: i });
|
|
288
|
+
}
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// parenthesis
|
|
293
|
+
if (parentheses.includes(char)) {
|
|
294
|
+
flushCurrent(char, i);
|
|
295
|
+
tokens.push({ type: "Parenthesis", value: char, pos: i });
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// array
|
|
300
|
+
if (char === "[") {
|
|
301
|
+
flushCurrent(char, i);
|
|
302
|
+
tokens.push({ type: "ArrayStart", pos: i });
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
if (char === "]") {
|
|
307
|
+
flushCurrent(char, i);
|
|
308
|
+
tokens.push({ type: "ArrayEnd", pos: i });
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// OBJECT START
|
|
313
|
+
if (char === "{") {
|
|
314
|
+
flushCurrent(char, i);
|
|
315
|
+
tokens.push({ type: "BlockStart", pos: i });
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// OBJECT END
|
|
320
|
+
if (char === "}") {
|
|
321
|
+
flushCurrent(char, i);
|
|
322
|
+
tokens.push({ type: "BlockEnd", pos: i });
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// comma
|
|
327
|
+
if (char === comma) {
|
|
328
|
+
flushCurrent(char, i);
|
|
329
|
+
tokens.push({ type: "Comma", pos: i });
|
|
330
|
+
continue;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// semicolon
|
|
334
|
+
if (char === semicolon) {
|
|
335
|
+
flushCurrent(char, i);
|
|
336
|
+
tokens.push({ type: "Semicolon", pos: i });
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// space
|
|
341
|
+
if (char === " ") {
|
|
342
|
+
flushCurrent(next, i);
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// build token
|
|
347
|
+
current += char;
|
|
348
|
+
|
|
349
|
+
if (i === expr.length - 1) {
|
|
350
|
+
flushCurrent(null, i);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
if (quote) throw new Error("Unclosed string literal");
|
|
355
|
+
|
|
356
|
+
// merge number + unit
|
|
357
|
+
const merged = [];
|
|
358
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
359
|
+
const t = tokens[i];
|
|
360
|
+
const next = tokens[i + 1];
|
|
361
|
+
|
|
362
|
+
if (t?.type === "Number" && next?.type === "Unit") {
|
|
363
|
+
merged.push({
|
|
364
|
+
type: "NumberWithUnit",
|
|
365
|
+
value: t.value,
|
|
366
|
+
unit: next.value,
|
|
367
|
+
pos: t.pos
|
|
368
|
+
});
|
|
369
|
+
i++;
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
merged.push(t);
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// implicit multiplication
|
|
377
|
+
const final = [];
|
|
378
|
+
for (let i = 0; i < merged.length; i++) {
|
|
379
|
+
const a = merged[i];
|
|
380
|
+
const b = merged[i + 1];
|
|
381
|
+
|
|
382
|
+
final.push(a);
|
|
383
|
+
|
|
384
|
+
if (
|
|
385
|
+
a && b &&
|
|
386
|
+
(
|
|
387
|
+
(["Number", "Identifier"].includes(a.type) ||
|
|
388
|
+
(a.type === "Parenthesis" && a.value === ")") ||
|
|
389
|
+
a.type === "ArrayEnd") &&
|
|
390
|
+
(["Identifier", "Function"].includes(b.type) ||
|
|
391
|
+
(b.type === "Parenthesis" && b.value === "("))
|
|
392
|
+
)
|
|
393
|
+
) {
|
|
394
|
+
final.push({ type: "Operator", value: "*", implicit: true });
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
return final;
|
|
145
399
|
}
|
|
146
400
|
|
|
147
|
-
function
|
|
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
|
-
|
|
401
|
+
function evaluateAST(node, context = {}) {
|
|
402
|
+
|
|
403
|
+
const vars = context.variables;
|
|
404
|
+
const fns = context.functions;
|
|
405
|
+
const units = context.units;
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
const isUnitObj = (v) =>
|
|
409
|
+
v && typeof v === "object" && "value" in v && "unit" in v;
|
|
410
|
+
|
|
411
|
+
const isComplex = (v) =>
|
|
412
|
+
v && typeof v === "object" && "re" in v && "im" in v;
|
|
413
|
+
|
|
414
|
+
const isSliceNode = (v) =>
|
|
415
|
+
v && typeof v === "object" && v.type === "SliceExpression";
|
|
416
|
+
|
|
417
|
+
const isMatrix = (v) =>
|
|
418
|
+
Array.isArray(v) && v.length > 0 && v.every(Array.isArray);
|
|
419
|
+
|
|
420
|
+
const normalizeMatrix = (value) => {
|
|
421
|
+
if (isMatrix(value)) return value.map((row) => [...row]);
|
|
422
|
+
if (Array.isArray(value)) return [value];
|
|
423
|
+
throw new Error("Expected matrix-compatible value");
|
|
424
|
+
};
|
|
425
|
+
|
|
426
|
+
const toOneBasedIndex = (value) => {
|
|
427
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
|
|
428
|
+
throw new Error("Matrix indices must be positive integers");
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
return value - 1;
|
|
432
|
+
};
|
|
433
|
+
|
|
434
|
+
const resolveSelector = (selector, contextLength) => {
|
|
435
|
+
if (isSliceNode(selector)) {
|
|
436
|
+
const startValue = selector.start == null ? 1 : evaluateAST(selector.start, context);
|
|
437
|
+
const endValue = selector.end == null ? contextLength : evaluateAST(selector.end, context);
|
|
438
|
+
const start = toOneBasedIndex(startValue);
|
|
439
|
+
const end = toOneBasedIndex(endValue);
|
|
440
|
+
|
|
441
|
+
if (end < start) {
|
|
442
|
+
return [];
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
const result = [];
|
|
446
|
+
for (let index = start; index <= end; index++) {
|
|
447
|
+
result.push(index);
|
|
448
|
+
}
|
|
449
|
+
return result;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
return [toOneBasedIndex(evaluateAST(selector, context))];
|
|
453
|
+
};
|
|
454
|
+
|
|
455
|
+
const indexMatrix = (matrix, selectors) => {
|
|
456
|
+
const target = normalizeMatrix(matrix);
|
|
457
|
+
|
|
458
|
+
if (selectors.length === 1) {
|
|
459
|
+
const rowIndexes = resolveSelector(selectors[0], target.length);
|
|
460
|
+
const rows = rowIndexes.map((rowIndex) => {
|
|
461
|
+
if (rowIndex >= target.length) {
|
|
462
|
+
throw new Error("Row index out of range");
|
|
463
|
+
}
|
|
464
|
+
return [...target[rowIndex]];
|
|
465
|
+
});
|
|
466
|
+
|
|
467
|
+
return rows.length === 1 ? rows[0] : rows;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
const rowIndexes = resolveSelector(selectors[0], target.length);
|
|
471
|
+
const colIndexes = resolveSelector(selectors[1], target[0]?.length || 0);
|
|
472
|
+
|
|
473
|
+
const values = rowIndexes.map((rowIndex) => {
|
|
474
|
+
if (rowIndex >= target.length) {
|
|
475
|
+
throw new Error("Row index out of range");
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
return colIndexes.map((colIndex) => {
|
|
479
|
+
if (colIndex >= target[rowIndex].length) {
|
|
480
|
+
throw new Error("Column index out of range");
|
|
481
|
+
}
|
|
482
|
+
return target[rowIndex][colIndex];
|
|
483
|
+
});
|
|
484
|
+
});
|
|
485
|
+
|
|
486
|
+
if (rowIndexes.length === 1 && colIndexes.length === 1) {
|
|
487
|
+
return values[0][0];
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
if (rowIndexes.length === 1) {
|
|
491
|
+
return values[0];
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
if (colIndexes.length === 1) {
|
|
495
|
+
return values.map((row) => [row[0]]);
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
return values;
|
|
499
|
+
};
|
|
500
|
+
|
|
501
|
+
const assignMatrixIndex = (matrix, selectors, value) => {
|
|
502
|
+
const target = isMatrix(matrix)
|
|
503
|
+
? matrix.map((row) => [...row])
|
|
504
|
+
: Array.isArray(matrix)
|
|
505
|
+
? [matrix.slice()]
|
|
506
|
+
: [];
|
|
507
|
+
|
|
508
|
+
const rowSelector = selectors[0];
|
|
509
|
+
const colSelector = selectors[1];
|
|
510
|
+
|
|
511
|
+
if (!rowSelector) {
|
|
512
|
+
throw new Error("Matrix assignment requires at least one index");
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
const rowContextLength = Math.max(target.length, 1);
|
|
516
|
+
const rowIndexes = resolveSelector(rowSelector, rowContextLength);
|
|
517
|
+
|
|
518
|
+
if (selectors.length === 1) {
|
|
519
|
+
const rowsValue = isMatrix(value) ? value : normalizeMatrix(value);
|
|
520
|
+
|
|
521
|
+
if (rowsValue.length !== rowIndexes.length) {
|
|
522
|
+
throw new Error("Assigned row count does not match slice");
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
rowIndexes.forEach((rowIndex, index) => {
|
|
526
|
+
target[rowIndex] = [...rowsValue[index]];
|
|
527
|
+
});
|
|
528
|
+
|
|
529
|
+
return {
|
|
530
|
+
updatedMatrix: target,
|
|
531
|
+
selectionResult: rowIndexes.length === 1 ? [target[rowIndexes[0]]] : rowIndexes.map((rowIndex) => [target[rowIndex]])
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
const maxCols = Math.max(...target.map((row) => row.length), 0, 1);
|
|
536
|
+
const colIndexes = resolveSelector(colSelector, maxCols);
|
|
537
|
+
const normalizedValue = normalizeMatrix(value);
|
|
538
|
+
|
|
539
|
+
if (normalizedValue.length !== rowIndexes.length) {
|
|
540
|
+
throw new Error("Assigned row count does not match matrix slice");
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
normalizedValue.forEach((row, rowOffset) => {
|
|
544
|
+
if (row.length !== colIndexes.length) {
|
|
545
|
+
throw new Error("Assigned column count does not match matrix slice");
|
|
546
|
+
}
|
|
547
|
+
});
|
|
548
|
+
|
|
549
|
+
rowIndexes.forEach((rowIndex, rowOffset) => {
|
|
550
|
+
if (!target[rowIndex]) {
|
|
551
|
+
target[rowIndex] = [];
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
colIndexes.forEach((colIndex, colOffset) => {
|
|
555
|
+
target[rowIndex][colIndex] = normalizedValue[rowOffset][colOffset];
|
|
556
|
+
});
|
|
557
|
+
});
|
|
558
|
+
|
|
559
|
+
return {
|
|
560
|
+
updatedMatrix: target,
|
|
561
|
+
selectionResult: rowIndexes.length === 1
|
|
562
|
+
? [colIndexes.map((colIndex) => target[rowIndexes[0]][colIndex])]
|
|
563
|
+
: rowIndexes.map((rowIndex) => colIndexes.map((colIndex) => target[rowIndex][colIndex]))
|
|
564
|
+
};
|
|
565
|
+
};
|
|
566
|
+
|
|
567
|
+
const multiplyMatrices = (left, right) => {
|
|
568
|
+
const a = normalizeMatrix(left);
|
|
569
|
+
const b = normalizeMatrix(right);
|
|
570
|
+
|
|
571
|
+
if (a[0].length !== b.length) {
|
|
572
|
+
throw new Error("Matrix dimensions do not allow multiplication");
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
return a.map((row) =>
|
|
576
|
+
b[0].map((_, colIndex) =>
|
|
577
|
+
row.reduce((sum, value, rowIndex) => sum + (value * b[rowIndex][colIndex]), 0)
|
|
578
|
+
)
|
|
579
|
+
);
|
|
580
|
+
};
|
|
581
|
+
|
|
582
|
+
const toComplex = (value) => {
|
|
583
|
+
if (isComplex(value)) return value;
|
|
584
|
+
if (typeof value === "number") return { re: value, im: 0 };
|
|
585
|
+
throw new Error("Complex arithmetic only supports numbers");
|
|
586
|
+
};
|
|
587
|
+
|
|
588
|
+
const fromImaginary = (value) => ({ re: 0, im: value });
|
|
589
|
+
|
|
590
|
+
const simplifyComplex = (value) =>
|
|
591
|
+
value.im === 0 ? value.re : value;
|
|
592
|
+
|
|
593
|
+
const evalComplexBinary = (operator, left, right) => {
|
|
594
|
+
const a = toComplex(left);
|
|
595
|
+
const b = toComplex(right);
|
|
596
|
+
|
|
597
|
+
switch (operator) {
|
|
598
|
+
case "+":
|
|
599
|
+
return simplifyComplex({ re: a.re + b.re, im: a.im + b.im });
|
|
600
|
+
case "-":
|
|
601
|
+
return simplifyComplex({ re: a.re - b.re, im: a.im - b.im });
|
|
602
|
+
case "*":
|
|
603
|
+
return simplifyComplex({
|
|
604
|
+
re: (a.re * b.re) - (a.im * b.im),
|
|
605
|
+
im: (a.re * b.im) + (a.im * b.re)
|
|
606
|
+
});
|
|
607
|
+
case "/": {
|
|
608
|
+
const denominator = (b.re ** 2) + (b.im ** 2);
|
|
609
|
+
|
|
610
|
+
if (denominator === 0) {
|
|
611
|
+
throw new Error("Division by zero");
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
return simplifyComplex({
|
|
615
|
+
re: ((a.re * b.re) + (a.im * b.im)) / denominator,
|
|
616
|
+
im: ((a.im * b.re) - (a.re * b.im)) / denominator
|
|
617
|
+
});
|
|
618
|
+
}
|
|
619
|
+
default:
|
|
620
|
+
throw new Error(`Operator ${operator} is not supported for complex numbers`);
|
|
621
|
+
}
|
|
622
|
+
};
|
|
623
|
+
|
|
624
|
+
/* ================= EVALUATOR ================= */
|
|
625
|
+
|
|
626
|
+
switch (node.type) {
|
|
627
|
+
|
|
628
|
+
/* ===== LITERAL ===== */
|
|
629
|
+
case "Literal":
|
|
630
|
+
return node.value;
|
|
631
|
+
|
|
632
|
+
case "ImaginaryLiteral":
|
|
633
|
+
return fromImaginary(node.value);
|
|
634
|
+
|
|
635
|
+
case "UnitLiteral":
|
|
636
|
+
return { value: node.value, unit: node.unit };
|
|
637
|
+
|
|
638
|
+
/* ===== VARIABLE ===== */
|
|
639
|
+
case "Identifier":
|
|
640
|
+
return vars.get(node.name);
|
|
641
|
+
|
|
642
|
+
/* ===== ASSIGNMENT ===== */
|
|
643
|
+
case "AssignmentExpression": {
|
|
644
|
+
const value = evaluateAST(node.right, context);
|
|
645
|
+
|
|
646
|
+
if (node.left.type === "Identifier") {
|
|
647
|
+
vars.set(node.left.name, value);
|
|
648
|
+
return value;
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
if (node.left.type === "IndexExpression" && node.left.object.type === "Identifier") {
|
|
652
|
+
const currentValue = vars.get(node.left.object.name);
|
|
653
|
+
const assigned = assignMatrixIndex(currentValue, node.left.selectors, value);
|
|
654
|
+
vars.set(node.left.object.name, assigned.updatedMatrix);
|
|
655
|
+
return assigned.selectionResult;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
throw new Error("Invalid assignment target");
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/* ===== UNARY ===== */
|
|
662
|
+
case "UnaryExpression": {
|
|
663
|
+
const val = evaluateAST(node.argument, context);
|
|
664
|
+
|
|
665
|
+
switch (node.operator) {
|
|
666
|
+
case "-":
|
|
667
|
+
return isComplex(val)
|
|
668
|
+
? simplifyComplex({ re: -val.re, im: -val.im })
|
|
669
|
+
: -val;
|
|
670
|
+
case "!": return !val;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
throw new Error(`Unknown unary operator ${node.operator}`);
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
/* ===== BINARY ===== */
|
|
677
|
+
case "BinaryExpression": {
|
|
678
|
+
let left = evaluateAST(node.left, context);
|
|
679
|
+
let right = evaluateAST(node.right, context);
|
|
680
|
+
|
|
681
|
+
// 🔥 UNIT handling
|
|
682
|
+
if (isUnitObj(left) || isUnitObj(right)) {
|
|
683
|
+
|
|
684
|
+
if (!units) throw new Error("Unit system not available");
|
|
685
|
+
|
|
686
|
+
return units.compute(node.operator, left, right);
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
if (node.operator === "*" && (Array.isArray(left) || Array.isArray(right))) {
|
|
690
|
+
return multiplyMatrices(left, right);
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
if (isComplex(left) || isComplex(right)) {
|
|
694
|
+
return evalComplexBinary(node.operator, left, right);
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
switch (node.operator) {
|
|
698
|
+
case "+": return left + right;
|
|
699
|
+
case "-": return left - right;
|
|
700
|
+
case "*": return left * right;
|
|
701
|
+
case "/": return left / right;
|
|
702
|
+
case "%": return left % right;
|
|
703
|
+
case "^": return left ** right;
|
|
704
|
+
|
|
705
|
+
case ">": return left > right;
|
|
706
|
+
case "<": return left < right;
|
|
707
|
+
case ">=": return left >= right;
|
|
708
|
+
case "<=": return left <= right;
|
|
709
|
+
case "==": return left === right;
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
throw new Error(`Unknown operator ${node.operator}`);
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
/* ===== LOGICAL ===== */
|
|
716
|
+
case "LogicalExpression": {
|
|
717
|
+
const left = evaluateAST(node.left, context);
|
|
718
|
+
|
|
719
|
+
if (node.operator === "&&") {
|
|
720
|
+
return left && evaluateAST(node.right, context);
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
if (node.operator === "||") {
|
|
724
|
+
return left || evaluateAST(node.right, context);
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
if (node.operator === "??") {
|
|
728
|
+
return left ?? evaluateAST(node.right, context);
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
throw new Error(`Unknown logical operator ${node.operator}`);
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
/* ===== FUNCTION CALL ===== */
|
|
735
|
+
case "CallExpression": {
|
|
736
|
+
const fnName = node.callee.name;
|
|
737
|
+
const fn = fns.get(fnName);
|
|
738
|
+
|
|
739
|
+
const args = node.arguments.map(arg =>
|
|
740
|
+
evaluateAST(arg, context)
|
|
741
|
+
);
|
|
742
|
+
|
|
743
|
+
return fn(...args);
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
/* ===== PIPELINE ===== */
|
|
747
|
+
case "PipelineExpression": {
|
|
748
|
+
const leftVal = evaluateAST(node.left, context);
|
|
749
|
+
|
|
750
|
+
// right must be function
|
|
751
|
+
if (node.right.type === "CallExpression") {
|
|
752
|
+
const fnName = node.right.callee.name;
|
|
753
|
+
const fn = fns.get(fnName);
|
|
754
|
+
|
|
755
|
+
const args = [
|
|
756
|
+
leftVal,
|
|
757
|
+
...node.right.arguments.map(arg =>
|
|
758
|
+
evaluateAST(arg, context)
|
|
759
|
+
)
|
|
760
|
+
];
|
|
761
|
+
|
|
762
|
+
return fn(...args);
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
if (node.right.type === "Identifier") {
|
|
766
|
+
const fn = fns.get(node.right.name);
|
|
767
|
+
return fn(leftVal);
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
throw new Error("Invalid pipeline target");
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
/* ===== UNIT CONVERSION ===== */
|
|
774
|
+
case "UnitConversion": {
|
|
775
|
+
const from = evaluateAST(node.from, context);
|
|
776
|
+
|
|
777
|
+
if (!isUnitObj(from)) {
|
|
778
|
+
throw new Error("Left side must be a unit value");
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
if (!units) {
|
|
782
|
+
throw new Error("Unit system not available");
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
return units.convert(from.value, from.unit, node.to);
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
/* ===== ARRAY ===== */
|
|
789
|
+
case "ArrayExpression":
|
|
790
|
+
return node.elements.map(el => evaluateAST(el, context));
|
|
791
|
+
|
|
792
|
+
case "IndexExpression": {
|
|
793
|
+
const target = evaluateAST(node.object, context);
|
|
794
|
+
return indexMatrix(target, node.selectors);
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/* ===== OBJECT ===== */
|
|
798
|
+
case "ObjectExpression": {
|
|
799
|
+
const obj = {};
|
|
800
|
+
for (let p of node.properties) {
|
|
801
|
+
obj[p.key] = evaluateAST(p.value, context);
|
|
802
|
+
}
|
|
803
|
+
return obj;
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
/* ===== MEMBER ===== */
|
|
807
|
+
case "MemberExpression": {
|
|
808
|
+
const obj = evaluateAST(node.object, context);
|
|
809
|
+
|
|
810
|
+
if (node.optional && obj == null) return undefined;
|
|
811
|
+
|
|
812
|
+
return obj[node.property.name];
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
default:
|
|
816
|
+
throw new Error(`Unknown AST node type: ${node.type}`);
|
|
817
|
+
}
|
|
224
818
|
}
|
|
225
819
|
|
|
226
|
-
function
|
|
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
|
-
result = mathOperations.power(a, b);
|
|
256
|
-
break;
|
|
257
|
-
case '*':
|
|
258
|
-
result = mathOperations.multiply(a, b);
|
|
259
|
-
break;
|
|
260
|
-
case '/':
|
|
261
|
-
result = mathOperations.divide(a, b);
|
|
262
|
-
break;
|
|
263
|
-
case '%':
|
|
264
|
-
result = mathOperations.modulus(a, b);
|
|
265
|
-
break;
|
|
266
|
-
case '+':
|
|
267
|
-
result = mathOperations.add(a, b);
|
|
268
|
-
break;
|
|
269
|
-
case '-':
|
|
270
|
-
result = mathOperations.subtract(a, b);
|
|
271
|
-
break;
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
stack.push(result);
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
if (stack.length !== 1) {
|
|
278
|
-
throw new Error("Invalid expression: leftover values in stack");
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
return stack[0];
|
|
820
|
+
function createContext({ variables, functions, units, evaluate}) {
|
|
821
|
+
if (!variables) throw new Error("Variable store missing");
|
|
822
|
+
if (!functions) throw new Error("Function registry missing");
|
|
823
|
+
if (!units) throw new Error("Units list missing");
|
|
824
|
+
if (!evaluate) throw new Error("evaluate function missing");
|
|
825
|
+
|
|
826
|
+
return {
|
|
827
|
+
variables: variables,
|
|
828
|
+
functions: functions,
|
|
829
|
+
units: units,
|
|
830
|
+
evaluate,
|
|
831
|
+
withScope(scope = {}) {
|
|
832
|
+
const tempVars = {
|
|
833
|
+
...variables.all?.(),
|
|
834
|
+
...scope
|
|
835
|
+
};
|
|
836
|
+
return createContext({
|
|
837
|
+
functions: functions,
|
|
838
|
+
evaluate,
|
|
839
|
+
units,
|
|
840
|
+
variables: {
|
|
841
|
+
get: (k) => tempVars[k],
|
|
842
|
+
set: (k, v) => (tempVars[k] = v),
|
|
843
|
+
all: () => tempVars
|
|
844
|
+
}
|
|
845
|
+
});
|
|
846
|
+
|
|
847
|
+
}
|
|
848
|
+
};
|
|
282
849
|
}
|
|
283
850
|
|
|
284
|
-
const isValidNumberPair = (a, b) =>
|
|
285
|
-
(typeof a === typeof b) &&
|
|
286
|
-
(typeof a === 'number' || typeof a === 'bigint');
|
|
287
|
-
|
|
288
|
-
const mathOperations = Object.freeze({
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
},
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
if (isValidNumberPair(a, b))
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
throw new Error("Invalid types for
|
|
315
|
-
},
|
|
316
|
-
|
|
317
|
-
add: function(a, b) {
|
|
318
|
-
if (isValidNumberPair(a, b)) return a + b;
|
|
319
|
-
if (typeof a === 'string' && typeof b === 'string') return a + b;
|
|
320
|
-
throw new Error("Invalid types for +");
|
|
321
|
-
},
|
|
322
|
-
subtract: function(a, b) {
|
|
323
|
-
if (isValidNumberPair(a, b)) return a - b;
|
|
324
|
-
throw new Error("Invalid types for -");
|
|
325
|
-
},
|
|
326
|
-
|
|
327
|
-
modulus: function(a, b) {
|
|
328
|
-
if (isValidNumberPair(a, b)) return a % b;
|
|
329
|
-
throw new Error("Invalid types for %");
|
|
330
|
-
}
|
|
331
|
-
});
|
|
851
|
+
const isValidNumberPair = (a, b) =>
|
|
852
|
+
(typeof a === typeof b) &&
|
|
853
|
+
(typeof a === 'number' || typeof a === 'bigint');
|
|
854
|
+
|
|
855
|
+
const mathOperations = Object.freeze({
|
|
856
|
+
power: function(a, b) {
|
|
857
|
+
if (isValidNumberPair(a, b)) return a ** b;
|
|
858
|
+
throw new Error("Invalid types for ^");
|
|
859
|
+
},
|
|
860
|
+
|
|
861
|
+
multiply: function(a, b) {
|
|
862
|
+
if (isValidNumberPair(a, b)) return a * b;
|
|
863
|
+
throw new Error("Invalid types for *");
|
|
864
|
+
},
|
|
865
|
+
|
|
866
|
+
divide: function(a, b) {
|
|
867
|
+
if (isValidNumberPair(a, b)) {
|
|
868
|
+
if (b === 0) throw new Error("Division by zero");
|
|
869
|
+
return a / b;
|
|
870
|
+
}
|
|
871
|
+
throw new Error("Invalid types for /");
|
|
872
|
+
},
|
|
873
|
+
|
|
874
|
+
add: function(a, b) {
|
|
875
|
+
if (isValidNumberPair(a, b)) return a + b;
|
|
876
|
+
if (typeof a === 'string' && typeof b === 'string') return a + b;
|
|
877
|
+
throw new Error("Invalid types for +");
|
|
878
|
+
},
|
|
879
|
+
subtract: function(a, b) {
|
|
880
|
+
if (isValidNumberPair(a, b)) return a - b;
|
|
881
|
+
throw new Error("Invalid types for -");
|
|
882
|
+
},
|
|
332
883
|
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
const gt = (a, b) => a > b;
|
|
338
|
-
const lt = (a, b) => a < b;
|
|
339
|
-
const eq = (a, b) => a === b;
|
|
340
|
-
const gte = (a, b) => a >= b;
|
|
341
|
-
const lte = (a, b) => a <= b;
|
|
342
|
-
|
|
343
|
-
const internalFunctions = Object.freeze({
|
|
344
|
-
|
|
345
|
-
max: (...args) => {
|
|
346
|
-
if (!args.every(v => typeof v === 'number')) {
|
|
347
|
-
throw new Error("max() expects numbers only");
|
|
348
|
-
}
|
|
349
|
-
return Math.max(...args);
|
|
350
|
-
},
|
|
351
|
-
|
|
352
|
-
min: (...args) => {
|
|
353
|
-
if (!args.every(v => typeof v === 'number')) {
|
|
354
|
-
throw new Error("min() expects numbers only");
|
|
355
|
-
}
|
|
356
|
-
return Math.min(...args);
|
|
357
|
-
},
|
|
358
|
-
|
|
359
|
-
and,
|
|
360
|
-
"&&": and,
|
|
361
|
-
|
|
362
|
-
or,
|
|
363
|
-
"||": or,
|
|
364
|
-
|
|
365
|
-
not,
|
|
366
|
-
"!": not,
|
|
367
|
-
|
|
368
|
-
greaterThan: gt,
|
|
369
|
-
">": gt,
|
|
370
|
-
|
|
371
|
-
lessThan: lt,
|
|
372
|
-
"<": lt,
|
|
373
|
-
|
|
374
|
-
isEqual: eq,
|
|
375
|
-
"==": eq,
|
|
376
|
-
|
|
377
|
-
greaterThanOrEqual: gte,
|
|
378
|
-
">=": gte,
|
|
379
|
-
|
|
380
|
-
lessThanOrEqual: lte,
|
|
381
|
-
"<=": lte,
|
|
382
|
-
|
|
383
|
-
if: (cond, t, f = false) => cond ? t : f
|
|
384
|
-
|
|
884
|
+
modulus: function(a, b) {
|
|
885
|
+
if (isValidNumberPair(a, b)) return a % b;
|
|
886
|
+
throw new Error("Invalid types for %");
|
|
887
|
+
}
|
|
385
888
|
});
|
|
386
889
|
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
//
|
|
403
|
-
if (
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
890
|
+
function createUnitsStore(initial = {}) {
|
|
891
|
+
let units = { ...initial};
|
|
892
|
+
|
|
893
|
+
// ---------- Helpers ----------
|
|
894
|
+
|
|
895
|
+
function getAllUnitsFlat() {
|
|
896
|
+
const result = new Set();
|
|
897
|
+
|
|
898
|
+
for (const type in units) {
|
|
899
|
+
for (const key in units[type]) {
|
|
900
|
+
const u = units[type][key];
|
|
901
|
+
|
|
902
|
+
const keyLower = key.toLowerCase();
|
|
903
|
+
result.add(keyLower);
|
|
904
|
+
|
|
905
|
+
// Unit name
|
|
906
|
+
if (u.unit) {
|
|
907
|
+
const unitLower = u.unit.toLowerCase();
|
|
908
|
+
|
|
909
|
+
// Avoid duplicate like "m" vs "meter"
|
|
910
|
+
if (unitLower !== keyLower) {
|
|
911
|
+
// Optional: only single-word units
|
|
912
|
+
if (unitLower.split(/\s+/).length === 1) {
|
|
913
|
+
result.add(unitLower);
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
// Symbol
|
|
919
|
+
if (u.symbol) {
|
|
920
|
+
const symbolLower = u.symbol.toLowerCase();
|
|
921
|
+
|
|
922
|
+
// Avoid duplicate with unit name
|
|
923
|
+
if (!u.unit || symbolLower !== u.unit.toLowerCase()) {
|
|
924
|
+
result.add(symbolLower);
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
return Array.from(result);
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
function findUnit(input) {
|
|
934
|
+
input = input.toLowerCase();
|
|
935
|
+
|
|
936
|
+
for (const type in units) {
|
|
937
|
+
for (const key in units[type]) {
|
|
938
|
+
const u = units[type][key];
|
|
939
|
+
|
|
940
|
+
if (
|
|
941
|
+
key.toLowerCase() === input ||
|
|
942
|
+
u.unit?.toLowerCase() === input ||
|
|
943
|
+
u.symbol?.toLowerCase() === input
|
|
944
|
+
) {
|
|
945
|
+
return { type, key , data: u};
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
return null;
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
// ---------- Core Convert ----------
|
|
954
|
+
|
|
955
|
+
function convert(value, fromUnit, toUnit) {
|
|
956
|
+
const from = findUnit(fromUnit);
|
|
957
|
+
const to = findUnit(toUnit);
|
|
958
|
+
|
|
959
|
+
if (!from) throw new Error(`Unknown unit: ${fromUnit}`);
|
|
960
|
+
if (!to) throw new Error(`Unknown unit: ${toUnit}`);
|
|
961
|
+
|
|
962
|
+
if (from.type !== to.type) {
|
|
963
|
+
throw new Error(`Cannot convert ${fromUnit} to ${toUnit} (${to.data.unit || to.key}). ${from.data.unit || from.key} conversion units like ${Object.keys(units[from.type]).join(", ")}`);
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
const result = value * (from.data.value / to.data.value);
|
|
967
|
+
|
|
968
|
+
return { value: result, unit: to.key };
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
// ---------- Public API ----------
|
|
972
|
+
|
|
973
|
+
return {
|
|
974
|
+
// Get all units
|
|
975
|
+
getUnits: () => units,
|
|
976
|
+
|
|
977
|
+
// Replace all units
|
|
978
|
+
setUnits: (newUnits) => {
|
|
979
|
+
units = { ...newUnits };
|
|
980
|
+
},
|
|
981
|
+
|
|
982
|
+
// Update single type
|
|
983
|
+
updateType: (type, data) => {
|
|
984
|
+
units[type] = { ...units[type], ...data };
|
|
985
|
+
},
|
|
986
|
+
|
|
987
|
+
// Add new unit
|
|
988
|
+
addUnit: (type, key, unitObj) => {
|
|
989
|
+
if (!units[type]) units[type] = {};
|
|
990
|
+
units[type][key] = unitObj;
|
|
991
|
+
},
|
|
992
|
+
compute(op, left, right) {
|
|
993
|
+
|
|
994
|
+
const isUnit = (v) =>
|
|
995
|
+
v && typeof v === "object" && "value" in v && "unit" in v;
|
|
996
|
+
|
|
997
|
+
const apply = (a, b) => {
|
|
998
|
+
switch (op) {
|
|
999
|
+
case "+": return a + b;
|
|
1000
|
+
case "-": return a - b;
|
|
1001
|
+
case "*": return a * b;
|
|
1002
|
+
case "/": return a / b;
|
|
1003
|
+
case "%": return a % b;
|
|
1004
|
+
case "^": return Math.pow(a, b);
|
|
1005
|
+
}
|
|
1006
|
+
};
|
|
1007
|
+
|
|
1008
|
+
// BOTH UNIT
|
|
1009
|
+
if (isUnit(left) && isUnit(right)) {
|
|
1010
|
+
|
|
1011
|
+
const from = this.findUnit(right.unit);
|
|
1012
|
+
const to = this.findUnit(left.unit);
|
|
1013
|
+
|
|
1014
|
+
if (from.type !== to.type) {
|
|
1015
|
+
throw new Error(`Cannot operate on different unit types`);
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
// convert right → left unit
|
|
1019
|
+
const r = right.value * (from.data.value / to.data.value);
|
|
1020
|
+
|
|
1021
|
+
const result = apply(left.value, r);
|
|
1022
|
+
|
|
1023
|
+
// multiplication/division produce compound units
|
|
1024
|
+
if (op === "*") {
|
|
1025
|
+
return { value: result, unit: left.unit };
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
if (op === "/") {
|
|
1029
|
+
return { value: result, unit: left.unit };
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
if (op === "^") {
|
|
1033
|
+
return { value: result, unit: left.unit };
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
return { value: result, unit: left.unit };
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
// ================= LEFT UNIT =================
|
|
1040
|
+
if (isUnit(left) && !isUnit(right)) {
|
|
1041
|
+
const result = apply(left.value, right);
|
|
1042
|
+
|
|
1043
|
+
return { value: result, unit: left.unit };
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
// ================= RIGHT UNIT =================
|
|
1047
|
+
if (!isUnit(left) && isUnit(right)) {
|
|
1048
|
+
const result = apply(left, right.value);
|
|
1049
|
+
|
|
1050
|
+
if (op === "/") {
|
|
1051
|
+
return { value: result, unit: right.unit };
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
return { value: result, unit: right.unit };
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
// ================= NORMAL =================
|
|
1058
|
+
return apply(left, right);
|
|
1059
|
+
},
|
|
1060
|
+
// Convert
|
|
1061
|
+
convert,
|
|
1062
|
+
|
|
1063
|
+
// Search helpers
|
|
1064
|
+
getAllUnitsFlat,
|
|
1065
|
+
findUnit
|
|
1066
|
+
};
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
const globalUnits = {
|
|
1070
|
+
// Length
|
|
1071
|
+
length: {
|
|
1072
|
+
m: { value: 1, unit: 'meter', symbol: 'm' },
|
|
1073
|
+
cm: { value: 0.01, unit: 'centimeter', symbol: 'cm' },
|
|
1074
|
+
mm: { value: 0.001, unit: 'millimeter', symbol: 'mm' },
|
|
1075
|
+
km: { value: 1000, unit: 'kilometer', symbol: 'km' },
|
|
1076
|
+
um: { value: 0.000001, unit: 'micrometer', symbol: 'um', note: 'also called micron' },
|
|
1077
|
+
nm: { value: 0.000000001, unit: 'nanometer', symbol: 'nm' },
|
|
1078
|
+
px: { value: 0.000264583, unit: 'pixel', symbol: 'px', note: '96dpi standard' },
|
|
1079
|
+
em: { value: 0.000264583 * 16, unit: 'em', symbol: 'em', note: '1em = 16px by default' },
|
|
1080
|
+
rem: { value: 0.000264583 * 16, unit: 'rem', symbol: 'rem', note: 'root em = 16px by default' },
|
|
1081
|
+
pt: { value: 0.000352778, unit: 'point', symbol: 'pt', note: '1pt = 1/72 inch' },
|
|
1082
|
+
pc: { value: 0.00423333, unit: 'pica', symbol: 'pc', note: '1pc = 12pt' },
|
|
1083
|
+
inch: { value: 0.0254, unit: 'inch', symbol: 'in' },
|
|
1084
|
+
ft: { value: 0.3048, unit: 'foot', symbol: 'ft' },
|
|
1085
|
+
yd: { value: 0.9144, unit: 'yard', symbol: 'yd' },
|
|
1086
|
+
mi: { value: 1609.344, unit: 'mile', symbol: 'mi' },
|
|
1087
|
+
thou: { value: 0.0000254, unit: 'mil', symbol: 'thou', note: 'thousandth of an inch' },
|
|
1088
|
+
furlong: { value: 201.168, unit: 'furlong', symbol: 'fur', note: '220 yards' },
|
|
1089
|
+
nmi: { value: 1852, unit: 'nautical mile', symbol: 'nmi' },
|
|
1090
|
+
fathom: { value: 1.8288, unit: 'fathom', symbol: 'fathom' },
|
|
1091
|
+
au: { value: 1.496e11, unit: 'astronomical unit', symbol: 'AU' },
|
|
1092
|
+
ly: { value: 9.4607e15, unit: 'light year', symbol: 'ly' },
|
|
1093
|
+
pc: { value: 3.0857e16, unit: 'parsec', symbol: 'pc' }
|
|
1094
|
+
},
|
|
1095
|
+
|
|
1096
|
+
// Weight / Mass
|
|
1097
|
+
weight: {
|
|
1098
|
+
mg: { value: 1e-6, unit: 'milligram', symbol: 'mg' },
|
|
1099
|
+
g: { value: 0.001, unit: 'gram', symbol: 'g' },
|
|
1100
|
+
kg: { value: 1, unit: 'kilogram', symbol: 'kg' },
|
|
1101
|
+
t: { value: 1000, unit: 'tonne', symbol: 't', note: 'metric ton' },
|
|
1102
|
+
lb: { value: 0.453592, unit: 'pound', symbol: 'lb' },
|
|
1103
|
+
oz: { value: 0.0283495, unit: 'ounce', symbol: 'oz' },
|
|
1104
|
+
stone: { value: 6.35029, unit: 'stone', symbol: 'st', note: '1 stone = 14 lb' }
|
|
1105
|
+
},
|
|
1106
|
+
|
|
1107
|
+
// Time
|
|
1108
|
+
time: {
|
|
1109
|
+
s: { value: 1, unit: 'second', symbol: 's' },
|
|
1110
|
+
min: { value: 60, unit: 'minute', symbol: 'min' },
|
|
1111
|
+
h: { value: 3600, unit: 'hour', symbol: 'h' },
|
|
1112
|
+
day: { value: 86400, unit: 'day', symbol: 'd' },
|
|
1113
|
+
week: { value: 604800, unit: 'week', symbol: 'wk' },
|
|
1114
|
+
month: { value: 2629800, unit: 'month', symbol: 'mo', note: 'average month = 30.44 days' },
|
|
1115
|
+
year: { value: 31557600, unit: 'year', symbol: 'yr', note: 'average year = 365.25 days' }
|
|
1116
|
+
},
|
|
1117
|
+
|
|
1118
|
+
// Voltage
|
|
1119
|
+
voltage: {
|
|
1120
|
+
V: { value: 1, unit: 'volt', symbol: 'V' },
|
|
1121
|
+
mV: { value: 0.001, unit: 'millivolt', symbol: 'mV' },
|
|
1122
|
+
kV: { value: 1000, unit: 'kilovolt', symbol: 'kV' },
|
|
1123
|
+
MV: { value: 1e6, unit: 'megavolt', symbol: 'MV' },
|
|
1124
|
+
GV: { value: 1e9, unit: 'gigavolt', symbol: 'GV' },
|
|
1125
|
+
statV: { value: 299.792458, unit: 'statvolt', symbol: 'statV', note: 'CGS unit' },
|
|
1126
|
+
abV: { value: 1e-8, unit: 'abvolt', symbol: 'abV', note: 'CGS electromagnetic unit' }
|
|
1127
|
+
},
|
|
1128
|
+
|
|
1129
|
+
// Frequency
|
|
1130
|
+
frequency: {
|
|
1131
|
+
Hz: { value: 1, unit: 'hertz', symbol: 'Hz', note: '1 cycle per second' },
|
|
1132
|
+
kHz: { value: 1e3, unit: 'kilohertz', symbol: 'kHz' },
|
|
1133
|
+
MHz: { value: 1e6, unit: 'megahertz', symbol: 'MHz' },
|
|
1134
|
+
GHz: { value: 1e9, unit: 'gigahertz', symbol: 'GHz' },
|
|
1135
|
+
THz: { value: 1e12, unit: 'terahertz', symbol: 'THz' }
|
|
1136
|
+
},
|
|
1137
|
+
|
|
1138
|
+
// Power
|
|
1139
|
+
power: {
|
|
1140
|
+
W: { value: 1, unit: 'watt', symbol: 'W', note: '1 joule per second' },
|
|
1141
|
+
mW: { value: 0.001, unit: 'milliwatt', symbol: 'mW' },
|
|
1142
|
+
kW: { value: 1000, unit: 'kilowatt', symbol: 'kW' },
|
|
1143
|
+
MW: { value: 1e6, unit: 'megawatt', symbol: 'MW' },
|
|
1144
|
+
GW: { value: 1e9, unit: 'gigawatt', symbol: 'GW' },
|
|
1145
|
+
HP: { value: 745.7, unit: 'horsepower', symbol: 'HP', note: 'mechanical HP = 745.7 W' },
|
|
1146
|
+
kcal_per_h: { value: 1.163, unit: 'kilocalorie per hour', symbol: 'kcal/h', note: '= 1.163 W' },
|
|
1147
|
+
BTU_per_h: { value: 0.29307107, unit: 'BTU per hour', symbol: 'BTU/h', note: '= 0.293 W' }
|
|
1148
|
+
},
|
|
1149
|
+
|
|
1150
|
+
// Sound
|
|
1151
|
+
sound: {
|
|
1152
|
+
dB: { value: 1, unit: 'decibel', symbol: 'dB', note: 'logarithmic unit of sound intensity' },
|
|
1153
|
+
dBA: { value: 1, unit: 'A-weighted decibel', symbol: 'dBA', note: 'Adjusted for human hearing' },
|
|
1154
|
+
dBC: { value: 1, unit: 'C-weighted decibel', symbol: 'dBC', note: 'Flat weighting for high-level sounds' }
|
|
1155
|
+
},
|
|
1156
|
+
|
|
1157
|
+
// Temperature
|
|
1158
|
+
temperature: {
|
|
1159
|
+
K: { value: 1, unit: 'kelvin', symbol: 'K' },
|
|
1160
|
+
C: { value: 1, unit: 'Celsius', symbol: '°C', note: '°C → K: add 273.15' },
|
|
1161
|
+
F: { value: 1, unit: 'Fahrenheit', symbol: '°F', note: '°F → K: (°F - 32) * 5/9 + 273.15' }
|
|
1162
|
+
},
|
|
1163
|
+
|
|
1164
|
+
// Pressure
|
|
1165
|
+
pressure: {
|
|
1166
|
+
Pa: { value: 1, unit: 'pascal', symbol: 'Pa' },
|
|
1167
|
+
kPa: { value: 1000, unit: 'kilopascal', symbol: 'kPa' },
|
|
1168
|
+
MPa: { value: 1e6, unit: 'megapascal', symbol: 'MPa' },
|
|
1169
|
+
bar: { value: 1e5, unit: 'bar', symbol: 'bar' },
|
|
1170
|
+
atm: { value: 101325, unit: 'atmosphere', symbol: 'atm' },
|
|
1171
|
+
psi: { value: 6894.757, unit: 'pound per square inch', symbol: 'psi' },
|
|
1172
|
+
mmHg:{ value: 133.322, unit: 'millimeter of mercury', symbol: 'mmHg' }
|
|
1173
|
+
},
|
|
1174
|
+
|
|
1175
|
+
// Energy
|
|
1176
|
+
energy: {
|
|
1177
|
+
J: { value: 1, unit: 'joule', symbol: 'J' },
|
|
1178
|
+
kJ: { value: 1000, unit: 'kilojoule', symbol: 'kJ' },
|
|
1179
|
+
cal: { value: 4.184, unit: 'calorie', symbol: 'cal' },
|
|
1180
|
+
kcal:{ value: 4184, unit: 'kilocalorie', symbol: 'kcal' },
|
|
1181
|
+
eV: { value: 1.60218e-19, unit: 'electronvolt', symbol: 'eV' },
|
|
1182
|
+
BTU: { value: 1055.06, unit: 'BTU', symbol: 'BTU' }
|
|
1183
|
+
},
|
|
1184
|
+
|
|
1185
|
+
// Force
|
|
1186
|
+
force: {
|
|
1187
|
+
N: { value: 1, unit: 'newton', symbol: 'N' },
|
|
1188
|
+
kN: { value: 1000, unit: 'kilonewton', symbol: 'kN' },
|
|
1189
|
+
lbf: { value: 4.44822, unit: 'pound-force', symbol: 'lbf' },
|
|
1190
|
+
kgf: { value: 9.80665, unit: 'kilogram-force', symbol: 'kgf' },
|
|
1191
|
+
dyne:{ value: 1e-5, unit: 'dyne', symbol: 'dyn' }
|
|
1192
|
+
},
|
|
1193
|
+
|
|
1194
|
+
// Area
|
|
1195
|
+
area: {
|
|
1196
|
+
m2: { value: 1, unit: 'square meter', symbol: 'm²' },
|
|
1197
|
+
cm2: { value: 0.0001, unit: 'square centimeter', symbol: 'cm²' },
|
|
1198
|
+
km2: { value: 1e6, unit: 'square kilometer', symbol: 'km²' },
|
|
1199
|
+
acre: { value: 4046.856, unit: 'acre', symbol: 'acre' },
|
|
1200
|
+
hectare:{ value: 10000, unit: 'hectare', symbol: 'ha' },
|
|
1201
|
+
ft2: { value: 0.092903, unit: 'square foot', symbol: 'ft²' },
|
|
1202
|
+
yd2: { value: 0.836127, unit: 'square yard', symbol: 'yd²' }
|
|
1203
|
+
},
|
|
1204
|
+
|
|
1205
|
+
// Volume
|
|
1206
|
+
volume: {
|
|
1207
|
+
m3: { value: 1, unit: 'cubic meter', symbol: 'm³' },
|
|
1208
|
+
L: { value: 0.001, unit: 'liter', symbol: 'L' },
|
|
1209
|
+
mL: { value: 1e-6, unit: 'milliliter', symbol: 'mL' },
|
|
1210
|
+
gallon:{ value: 0.00378541, unit: 'US gallon', symbol: 'gal' },
|
|
1211
|
+
pint: { value: 0.000473176, unit: 'US pint', symbol: 'pt' },
|
|
1212
|
+
floz: { value: 2.9574e-5, unit: 'US fluid ounce', symbol: 'fl oz' }
|
|
1213
|
+
},
|
|
1214
|
+
|
|
1215
|
+
// Electrical Current
|
|
1216
|
+
current: {
|
|
1217
|
+
A: { value: 1, unit: 'ampere', symbol: 'A' },
|
|
1218
|
+
mA: { value: 0.001, unit: 'milliampere', symbol: 'mA' },
|
|
1219
|
+
uA: { value: 0.000001, unit: 'microampere', symbol: 'uA' },
|
|
1220
|
+
kA: { value: 1000, unit: 'kiloampere', symbol: 'kA' }
|
|
1221
|
+
},
|
|
1222
|
+
|
|
1223
|
+
// Resistance / Conductance
|
|
1224
|
+
resistance: {
|
|
1225
|
+
ohm: { value: 1, unit: 'ohm' },
|
|
1226
|
+
kohm: { value: 1000, unit: 'kiloohm'},
|
|
1227
|
+
megaohm: { value: 1e6, unit: 'megaohm'},
|
|
1228
|
+
S: { value: 1, unit: 'siemens', symbol: 'S', note: 'conductance' }
|
|
1229
|
+
},
|
|
1230
|
+
|
|
1231
|
+
// Capacitance / Inductance
|
|
1232
|
+
capacitance: {
|
|
1233
|
+
F: { value: 1, unit: 'farad', symbol: 'F' },
|
|
1234
|
+
mF: { value: 0.001, unit: 'millifarad'},
|
|
1235
|
+
uF: { value: 0.000001, unit: 'microfarad' }
|
|
1236
|
+
},
|
|
1237
|
+
inductance: {
|
|
1238
|
+
H: { value: 1, unit: 'henry', symbol: 'H' },
|
|
1239
|
+
mH: { value: 0.001, unit: 'millihenry', symbol: 'mH' },
|
|
1240
|
+
uH: { value: 0.000001, unit: 'microhenry', symbol: 'uH' }
|
|
1241
|
+
},
|
|
1242
|
+
|
|
1243
|
+
// Luminous Intensity / Illuminance
|
|
1244
|
+
light: {
|
|
1245
|
+
cd: { value: 1, unit: 'candela', symbol: 'cd' },
|
|
1246
|
+
lm: { value: 1, unit: 'lumen', symbol: 'lm' },
|
|
1247
|
+
lx: { value: 1, unit: 'lux', symbol: 'lx' }
|
|
1248
|
+
},
|
|
1249
|
+
|
|
1250
|
+
// Data / Digital Storage
|
|
1251
|
+
data: {
|
|
1252
|
+
bit: { value: 1, unit: 'bit', symbol: 'bit' },
|
|
1253
|
+
B: { value: 8, unit: 'byte', symbol: 'B' },
|
|
1254
|
+
KB: { value: 8e3, unit: 'kilobyte', symbol: 'KB' },
|
|
1255
|
+
MB: { value: 8e6, unit: 'megabyte', symbol: 'MB' },
|
|
1256
|
+
GB: { value: 8e9, unit: 'gigabyte', symbol: 'GB' },
|
|
1257
|
+
TB: { value: 8e12, unit: 'terabyte', symbol: 'TB' }
|
|
1258
|
+
},
|
|
1259
|
+
|
|
1260
|
+
// Angle
|
|
1261
|
+
angle: {
|
|
1262
|
+
deg: { value: 1, unit: 'degree', symbol: '°' },
|
|
1263
|
+
rad: { value: 57.2958, unit: 'radian', symbol: 'rad', note: '1 rad = 57.2958°' },
|
|
1264
|
+
grad:{ value: 0.9, unit: 'grad', symbol: 'grad', note: '1 grad = 0.9°' }
|
|
1265
|
+
},
|
|
1266
|
+
radiation: {
|
|
1267
|
+
// Absorbed Dose
|
|
1268
|
+
Gy: { value: 1, unit: 'gray', symbol: 'Gy', note: 'Absorbed dose: 1 Gy = 1 J/kg' },
|
|
1269
|
+
mGy: { value: 0.001, unit: 'milligray', symbol: 'mGy' },
|
|
1270
|
+
rad: { value: 0.01, unit: 'rad', symbol: 'rad', note: '1 rad = 0.01 Gy' },
|
|
1271
|
+
|
|
1272
|
+
// Dose Equivalent
|
|
1273
|
+
Sv: { value: 1, unit: 'sievert', symbol: 'Sv', note: 'Biological effect dose equivalent' },
|
|
1274
|
+
mSv: { value: 0.001, unit: 'millisievert', symbol: 'mSv' },
|
|
1275
|
+
rem: { value: 0.01, unit: 'rem', symbol: 'rem', note: '1 rem = 0.01 Sv' },
|
|
1276
|
+
|
|
1277
|
+
// Radioactivity
|
|
1278
|
+
Bq: { value: 1, unit: 'becquerel', symbol: 'Bq', note: '1 decay per second' },
|
|
1279
|
+
kBq: { value: 1e3, unit: 'kilobecquerel', symbol: 'kBq' },
|
|
1280
|
+
MBq: { value: 1e6, unit: 'megabecquerel', symbol: 'MBq' },
|
|
1281
|
+
GBq: { value: 1e9, unit: 'gigabecquerel', symbol: 'GBq' },
|
|
1282
|
+
Ci: { value: 3.7e10, unit: 'curie', symbol: 'Ci', note: '1 Ci = 3.7 x 10¹⁰ decays per second' },
|
|
1283
|
+
mCi: { value: 3.7e7, unit: 'millicurie', symbol: 'mCi' }
|
|
1284
|
+
}
|
|
1285
|
+
};
|
|
1286
|
+
|
|
1287
|
+
const validVarName = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
|
|
1288
|
+
|
|
1289
|
+
function createVarStore(initial = {}) {
|
|
1290
|
+
let store = Object.create(null);
|
|
1291
|
+
|
|
1292
|
+
|
|
1293
|
+
for (const key in initial) {
|
|
1294
|
+
store[key] = initial[key];
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
return {
|
|
1298
|
+
set(name, value, { override = true } = {}) {
|
|
1299
|
+
|
|
1300
|
+
// Name validation
|
|
1301
|
+
if (typeof name !== "string" || !name) {
|
|
1302
|
+
throw new Error("Variable name must be a non-empty string");
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
if (!validVarName.test(name)) {
|
|
1306
|
+
throw new Error(`Variable Name Error: '${name}' is not a valid variable name`);
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
// Value validation
|
|
1310
|
+
if (value === undefined) {
|
|
1311
|
+
throw new Error(`Variable Value Error: '${name}' cannot be undefined`);
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
// Prevent overwrite (optional)
|
|
1315
|
+
if (!override && name in variablesDB) {
|
|
1316
|
+
throw new Error(`Variable '${name}' already exists`);
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1319
|
+
store[name] = value;
|
|
1320
|
+
},
|
|
1321
|
+
|
|
1322
|
+
//get variable
|
|
1323
|
+
get(name) {
|
|
1324
|
+
return store[name];
|
|
1325
|
+
},
|
|
1326
|
+
|
|
1327
|
+
// check existence
|
|
1328
|
+
has(name) {
|
|
1329
|
+
return Object.prototype.hasOwnProperty.call(store, name);
|
|
1330
|
+
},
|
|
1331
|
+
|
|
1332
|
+
// remove variable
|
|
1333
|
+
remove(name) {
|
|
1334
|
+
delete store[name];
|
|
1335
|
+
},
|
|
1336
|
+
|
|
1337
|
+
// get all variables (snapshot)
|
|
1338
|
+
all() {
|
|
1339
|
+
return { ...store };
|
|
1340
|
+
},
|
|
1341
|
+
|
|
1342
|
+
// clear all
|
|
1343
|
+
clear() {
|
|
1344
|
+
store = Object.create(null);
|
|
1345
|
+
},
|
|
1346
|
+
|
|
1347
|
+
// merge multiple variables
|
|
1348
|
+
merge(obj = {}) {
|
|
1349
|
+
for (const key in obj) {
|
|
1350
|
+
store[key] = obj[key];
|
|
1351
|
+
}
|
|
1352
|
+
},
|
|
1353
|
+
|
|
1354
|
+
// clone store (for scoped instances)
|
|
1355
|
+
clone() {
|
|
1356
|
+
return createVarStore(store);
|
|
1357
|
+
}
|
|
1358
|
+
};
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
function createFunctionRegistry(initial = {}) {
|
|
1362
|
+
const store = Object.create(null);
|
|
1363
|
+
|
|
1364
|
+
for (const key in initial) {
|
|
1365
|
+
if (typeof initial[key] === "function") {
|
|
1366
|
+
store[key] = initial[key];
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
return {
|
|
1371
|
+
getAllFunctionsName() {
|
|
1372
|
+
return Object.keys(store);
|
|
1373
|
+
},
|
|
1374
|
+
// register new formula
|
|
1375
|
+
register(name, fn) {
|
|
1376
|
+
if (typeof name !== "string" || !name) {
|
|
1377
|
+
throw new Error("Formula name must be a non-empty string");
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
if (typeof fn !== "function") {
|
|
1381
|
+
throw new Error(`Formula "${name}" must be callable`);
|
|
1382
|
+
}
|
|
1383
|
+
|
|
1384
|
+
store[name] = fn;
|
|
1385
|
+
},
|
|
1386
|
+
|
|
1387
|
+
// get formula
|
|
1388
|
+
get(name) {
|
|
1389
|
+
return store[name];
|
|
1390
|
+
},
|
|
1391
|
+
|
|
1392
|
+
// check existence
|
|
1393
|
+
has(name) {
|
|
1394
|
+
return Object.prototype.hasOwnProperty.call(store, name);
|
|
1395
|
+
},
|
|
1396
|
+
|
|
1397
|
+
// remove formula
|
|
1398
|
+
remove(name) {
|
|
1399
|
+
delete store[name];
|
|
1400
|
+
},
|
|
1401
|
+
|
|
1402
|
+
// list all
|
|
1403
|
+
all() {
|
|
1404
|
+
return { ...store };
|
|
1405
|
+
},
|
|
1406
|
+
|
|
1407
|
+
// clear registry
|
|
1408
|
+
clear() {
|
|
1409
|
+
for (const key in store) {
|
|
1410
|
+
delete store[key];
|
|
1411
|
+
}
|
|
1412
|
+
},
|
|
1413
|
+
|
|
1414
|
+
// extend multiple
|
|
1415
|
+
extend(formulas = {}) {
|
|
1416
|
+
for (const name in formulas) {
|
|
1417
|
+
if (typeof formulas[name] === "function") {
|
|
1418
|
+
store[name] = formulas[name];
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
},
|
|
1422
|
+
|
|
1423
|
+
// clone (for scoped instances)
|
|
1424
|
+
clone() {
|
|
1425
|
+
return createFormulaRegistry(store);
|
|
1426
|
+
}
|
|
1427
|
+
};
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
function validateSquareMatrix(matrix) {
|
|
1431
|
+
if (!Array.isArray(matrix) || matrix.length === 0) {
|
|
1432
|
+
throw new Error("det() expects a non-empty matrix");
|
|
1433
|
+
}
|
|
1434
|
+
|
|
1435
|
+
if (!matrix.every(Array.isArray)) {
|
|
1436
|
+
throw new Error("det() expects a 2D matrix");
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
const size = matrix.length;
|
|
1440
|
+
if (!matrix.every((row) => row.length === size)) {
|
|
1441
|
+
throw new Error("det() expects a square matrix");
|
|
1442
|
+
}
|
|
1443
|
+
|
|
1444
|
+
for (const row of matrix) {
|
|
1445
|
+
for (const value of row) {
|
|
1446
|
+
if (typeof value !== "number" && typeof value !== "bigint") {
|
|
1447
|
+
throw new Error("det() matrix values must be numeric");
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
|
|
1453
|
+
function determinant(matrix) {
|
|
1454
|
+
validateSquareMatrix(matrix);
|
|
1455
|
+
|
|
1456
|
+
if (matrix.length === 1) {
|
|
1457
|
+
return matrix[0][0];
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
if (matrix.length === 2) {
|
|
1461
|
+
return (matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]);
|
|
1462
|
+
}
|
|
1463
|
+
|
|
1464
|
+
return matrix[0].reduce((sum, value, columnIndex) => {
|
|
1465
|
+
const minor = matrix.slice(1).map((row) =>
|
|
1466
|
+
row.filter((_, index) => index !== columnIndex)
|
|
1467
|
+
);
|
|
1468
|
+
const cofactor = columnIndex % 2 === 0 ? value : -value;
|
|
1469
|
+
return sum + (cofactor * determinant(minor));
|
|
1470
|
+
}, 0);
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
function splitTerms(expression) {
|
|
1474
|
+
const normalized = expression.replace(/\s+/g, "");
|
|
1475
|
+
if (!normalized) {
|
|
1476
|
+
return [];
|
|
1477
|
+
}
|
|
1478
|
+
|
|
1479
|
+
return normalized
|
|
1480
|
+
.replace(/-/g, "+-")
|
|
1481
|
+
.split("+")
|
|
1482
|
+
.filter(Boolean);
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
function parsePolynomial(expression, variable) {
|
|
1486
|
+
const terms = splitTerms(expression);
|
|
1487
|
+
const coefficients = new Map();
|
|
1488
|
+
|
|
1489
|
+
for (const term of terms) {
|
|
1490
|
+
if (term.includes(variable)) {
|
|
1491
|
+
const [rawCoeff, rawPower] = term.split(variable);
|
|
1492
|
+
let coefficient;
|
|
1493
|
+
|
|
1494
|
+
if (rawCoeff === "" || rawCoeff === "+") coefficient = 1;
|
|
1495
|
+
else if (rawCoeff === "-") coefficient = -1;
|
|
1496
|
+
else {
|
|
1497
|
+
const cleaned = rawCoeff.endsWith("*") ? rawCoeff.slice(0, -1) : rawCoeff;
|
|
1498
|
+
coefficient = Number(cleaned);
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
if (!Number.isFinite(coefficient)) {
|
|
1502
|
+
throw new Error("Unsupported algebra term");
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
let power = 1;
|
|
1506
|
+
if (rawPower) {
|
|
1507
|
+
if (!rawPower.startsWith("^")) {
|
|
1508
|
+
throw new Error("Unsupported algebra term");
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
power = Number(rawPower.slice(1));
|
|
1512
|
+
}
|
|
1513
|
+
|
|
1514
|
+
if (!Number.isInteger(power) || power < 0) {
|
|
1515
|
+
throw new Error("Only non-negative integer powers are supported");
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
coefficients.set(power, (coefficients.get(power) || 0) + coefficient);
|
|
1519
|
+
} else {
|
|
1520
|
+
const constant = Number(term);
|
|
1521
|
+
if (!Number.isFinite(constant)) {
|
|
1522
|
+
throw new Error("Unsupported algebra term");
|
|
1523
|
+
}
|
|
1524
|
+
coefficients.set(0, (coefficients.get(0) || 0) + constant);
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
return coefficients;
|
|
1529
|
+
}
|
|
1530
|
+
|
|
1531
|
+
function formatPolynomial(coefficients, variable) {
|
|
1532
|
+
const ordered = [...coefficients.entries()]
|
|
1533
|
+
.filter(([, coefficient]) => coefficient !== 0)
|
|
1534
|
+
.sort((a, b) => b[0] - a[0]);
|
|
1535
|
+
|
|
1536
|
+
if (!ordered.length) {
|
|
1537
|
+
return "0";
|
|
1538
|
+
}
|
|
1539
|
+
|
|
1540
|
+
return ordered.map(([power, coefficient], index) => {
|
|
1541
|
+
const negative = coefficient < 0;
|
|
1542
|
+
const absCoeff = Math.abs(coefficient);
|
|
1543
|
+
let body;
|
|
1544
|
+
|
|
1545
|
+
if (power === 0) {
|
|
1546
|
+
body = `${absCoeff}`;
|
|
1547
|
+
} else if (power === 1) {
|
|
1548
|
+
body = absCoeff === 1 ? variable : `${absCoeff} * ${variable}`;
|
|
1549
|
+
} else {
|
|
1550
|
+
body = absCoeff === 1
|
|
1551
|
+
? `${variable}^${power}`
|
|
1552
|
+
: `${absCoeff} * ${variable}^${power}`;
|
|
1553
|
+
}
|
|
1554
|
+
|
|
1555
|
+
if (index === 0) {
|
|
1556
|
+
return negative ? `-${body}` : body;
|
|
1557
|
+
}
|
|
1558
|
+
|
|
1559
|
+
return negative ? `- ${body}` : `+ ${body}`;
|
|
1560
|
+
}).join(" ");
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
function simplifyExpression(expression) {
|
|
1564
|
+
const compact = expression.replace(/\s+/g, "");
|
|
1565
|
+
const variableMatch = compact.match(/[a-zA-Z]+/);
|
|
1566
|
+
const variable = variableMatch?.[0] || "x";
|
|
1567
|
+
const coefficients = parsePolynomial(expression, variable);
|
|
1568
|
+
return formatPolynomial(coefficients, variable);
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
function derivativeExpression(expression, variable) {
|
|
1572
|
+
const coefficients = parsePolynomial(expression, variable);
|
|
1573
|
+
const derived = new Map();
|
|
1574
|
+
|
|
1575
|
+
for (const [power, coefficient] of coefficients.entries()) {
|
|
1576
|
+
if (power === 0) continue;
|
|
1577
|
+
derived.set(power - 1, (derived.get(power - 1) || 0) + (coefficient * power));
|
|
1578
|
+
}
|
|
1579
|
+
|
|
1580
|
+
return formatPolynomial(derived, variable);
|
|
1581
|
+
}
|
|
1582
|
+
|
|
1583
|
+
const internalFunctions = {
|
|
1584
|
+
max: (...args) => {
|
|
1585
|
+
if (!args.length) throw new Error("max() requires arguments");
|
|
1586
|
+
return Math.max(...args);
|
|
1587
|
+
},
|
|
1588
|
+
|
|
1589
|
+
min: (...args) => {
|
|
1590
|
+
if (!args.length) throw new Error("min() requires arguments");
|
|
1591
|
+
return Math.min(...args);
|
|
1592
|
+
},
|
|
1593
|
+
|
|
1594
|
+
abs: (x) => Math.abs(x),
|
|
1595
|
+
|
|
1596
|
+
round: (x) => Math.round(x),
|
|
1597
|
+
|
|
1598
|
+
floor: (x) => Math.floor(x),
|
|
1599
|
+
|
|
1600
|
+
ceil: (x) => Math.ceil(x),
|
|
1601
|
+
|
|
1602
|
+
sqrt: (x) => {
|
|
1603
|
+
if (x < 0) throw new Error("sqrt() domain error");
|
|
1604
|
+
return Math.sqrt(x);
|
|
1605
|
+
},
|
|
1606
|
+
|
|
1607
|
+
pow: (a, b) => a ** b,
|
|
1608
|
+
det: (matrix) => determinant(matrix),
|
|
1609
|
+
simplify: (expression) => {
|
|
1610
|
+
if (typeof expression !== "string") {
|
|
1611
|
+
throw new Error("simplify() expects an expression string");
|
|
1612
|
+
}
|
|
1613
|
+
return simplifyExpression(expression);
|
|
1614
|
+
},
|
|
1615
|
+
derivative: (expression, variable = "x") => {
|
|
1616
|
+
if (typeof expression !== "string" || typeof variable !== "string") {
|
|
1617
|
+
throw new Error("derivative() expects expression and variable strings");
|
|
1618
|
+
}
|
|
1619
|
+
return derivativeExpression(expression, variable);
|
|
1620
|
+
},
|
|
1621
|
+
|
|
1622
|
+
/* ================= TRIGONOMETRY ================= */
|
|
1623
|
+
|
|
1624
|
+
sin: (x) => Math.sin(x),
|
|
1625
|
+
cos: (x) => Math.cos(x),
|
|
1626
|
+
tan: (x) => Math.tan(x),
|
|
1627
|
+
|
|
1628
|
+
asin: (x) => Math.asin(x),
|
|
1629
|
+
acos: (x) => Math.acos(x),
|
|
1630
|
+
atan: (x) => Math.atan(x),
|
|
1631
|
+
|
|
1632
|
+
/* ================= LOG / EXP ================= */
|
|
1633
|
+
|
|
1634
|
+
log: (x) => {
|
|
1635
|
+
if (x <= 0) throw new Error("log() domain error");
|
|
1636
|
+
return Math.log(x);
|
|
1637
|
+
},
|
|
1638
|
+
|
|
1639
|
+
log10: (x) => {
|
|
1640
|
+
if (x <= 0) throw new Error("log10() domain error");
|
|
1641
|
+
return Math.log10(x);
|
|
1642
|
+
},
|
|
1643
|
+
|
|
1644
|
+
exp: (x) => Math.exp(x),
|
|
1645
|
+
|
|
1646
|
+
/* ================= RANDOM ================= */
|
|
1647
|
+
|
|
1648
|
+
random: () => Math.random(),
|
|
1649
|
+
|
|
1650
|
+
/* ================= BOOLEAN / LOGIC ================= */
|
|
1651
|
+
|
|
1652
|
+
and: (a, b) => Boolean(a && b),
|
|
1653
|
+
|
|
1654
|
+
or: (a, b) => Boolean(a || b),
|
|
1655
|
+
|
|
1656
|
+
not: (a) => !a,
|
|
1657
|
+
"!": (a) => !a,
|
|
1658
|
+
|
|
1659
|
+
/* ================= COMPARISON ================= */
|
|
1660
|
+
|
|
1661
|
+
eq: (a, b) => a === b,
|
|
1662
|
+
|
|
1663
|
+
neq: (a, b) => a !== b,
|
|
1664
|
+
"notEqual": (a, b) => a !== b,
|
|
1665
|
+
|
|
1666
|
+
gt: (a, b) => a > b,
|
|
1667
|
+
"greaterThan": (a, b) => a > b,
|
|
1668
|
+
|
|
1669
|
+
lt: (a, b) => a < b,
|
|
1670
|
+
"lessThan": (a, b) => a < b,
|
|
1671
|
+
|
|
1672
|
+
gte: (a, b) => a >= b,
|
|
1673
|
+
"greaterThanOrEqual": (a, b) => a >= b,
|
|
1674
|
+
|
|
1675
|
+
lte: (a, b) => a <= b,
|
|
1676
|
+
"lessThanOrEqual": (a, b) => a <= b,
|
|
1677
|
+
|
|
1678
|
+
/* ================= UTILITY ================= */
|
|
1679
|
+
|
|
1680
|
+
clamp: (x, min, max) => {
|
|
1681
|
+
if (min > max) throw new Error("clamp(): min > max");
|
|
1682
|
+
return Math.min(Math.max(x, min), max);
|
|
1683
|
+
},
|
|
1684
|
+
|
|
1685
|
+
if: (condition, a, b) => (condition ? a : b),
|
|
1686
|
+
|
|
1687
|
+
/* ================= TYPE ================= */
|
|
1688
|
+
|
|
1689
|
+
typeof: (x) => typeof x,
|
|
1690
|
+
|
|
1691
|
+
/* ================= STRING ================= */
|
|
1692
|
+
|
|
1693
|
+
length: (x) => {
|
|
1694
|
+
if (typeof x === "string" || Array.isArray(x)) {
|
|
1695
|
+
return x.length;
|
|
1696
|
+
}
|
|
1697
|
+
throw new Error("length() expects string or array");
|
|
1698
|
+
}
|
|
1699
|
+
};
|
|
1700
|
+
|
|
1701
|
+
function buildAST(tokens) {
|
|
1702
|
+
let current = 0;
|
|
1703
|
+
|
|
1704
|
+
const peek = () => tokens[current];
|
|
1705
|
+
const consume = () => tokens[current++];
|
|
1706
|
+
|
|
1707
|
+
const match = (type, value) => {
|
|
1708
|
+
const t = peek();
|
|
1709
|
+
if (!t) return false;
|
|
1710
|
+
|
|
1711
|
+
if (t.type !== type) return false;
|
|
1712
|
+
|
|
1713
|
+
if (value !== undefined && t.value !== value) return false;
|
|
1714
|
+
|
|
1715
|
+
current++;
|
|
1716
|
+
return true;
|
|
1717
|
+
};
|
|
1718
|
+
|
|
1719
|
+
const parseSliceOrIndex = () => {
|
|
1720
|
+
let start = null;
|
|
1721
|
+
|
|
1722
|
+
if (!(peek()?.type === "Colon" || peek()?.type === "Comma" || peek()?.type === "ArrayEnd")) {
|
|
1723
|
+
start = parseExpression();
|
|
1724
|
+
}
|
|
1725
|
+
|
|
1726
|
+
if (match("Colon")) {
|
|
1727
|
+
let end = null;
|
|
1728
|
+
|
|
1729
|
+
if (!(peek()?.type === "Comma" || peek()?.type === "ArrayEnd")) {
|
|
1730
|
+
end = parseExpression();
|
|
1731
|
+
}
|
|
1732
|
+
|
|
1733
|
+
return {
|
|
1734
|
+
type: "SliceExpression",
|
|
1735
|
+
start,
|
|
1736
|
+
end
|
|
1737
|
+
};
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
return start;
|
|
1741
|
+
};
|
|
1742
|
+
|
|
1743
|
+
/* ================= PRIMARY ================= */
|
|
1744
|
+
function parsePrimary() {
|
|
1745
|
+
const token = consume();
|
|
1746
|
+
if (!token) throw new Error("Unexpected end of input");
|
|
1747
|
+
|
|
1748
|
+
switch (token.type) {
|
|
1749
|
+
case "Number":
|
|
1750
|
+
case "BigInt":
|
|
1751
|
+
case "Boolean":
|
|
1752
|
+
case "String":
|
|
1753
|
+
return { type: "Literal", value: token.value };
|
|
1754
|
+
|
|
1755
|
+
case "ImaginaryLiteral":
|
|
1756
|
+
return { type: "ImaginaryLiteral", value: token.value };
|
|
1757
|
+
|
|
1758
|
+
case "NumberWithUnit":
|
|
1759
|
+
return {
|
|
1760
|
+
type: "UnitLiteral",
|
|
1761
|
+
value: token.value,
|
|
1762
|
+
unit: token.unit
|
|
1763
|
+
};
|
|
1764
|
+
|
|
1765
|
+
case "Identifier":
|
|
1766
|
+
return { type: "Identifier", name: token.name };
|
|
1767
|
+
|
|
1768
|
+
case "Function": // 🔥 ADD THIS
|
|
1769
|
+
return {
|
|
1770
|
+
type: "Identifier",
|
|
1771
|
+
name: token.name
|
|
1772
|
+
};
|
|
1773
|
+
|
|
1774
|
+
case "Parenthesis":
|
|
1775
|
+
if (token.value === "(") {
|
|
1776
|
+
const expr = parseExpression();
|
|
1777
|
+
|
|
1778
|
+
if (!match("Parenthesis", ")")) {
|
|
1779
|
+
throw new Error(`Expected ')'`);
|
|
1780
|
+
}
|
|
1781
|
+
|
|
1782
|
+
return expr;
|
|
1783
|
+
}
|
|
1784
|
+
|
|
1785
|
+
case "ArrayStart": {
|
|
1786
|
+
const rows = [];
|
|
1787
|
+
let currentRow = [];
|
|
1788
|
+
|
|
1789
|
+
if (!match("ArrayEnd")) {
|
|
1790
|
+
while (true) {
|
|
1791
|
+
currentRow.push(parseExpression());
|
|
1792
|
+
|
|
1793
|
+
if (match("Comma")) {
|
|
1794
|
+
continue;
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1797
|
+
if (match("Semicolon")) {
|
|
1798
|
+
rows.push(currentRow);
|
|
1799
|
+
currentRow = [];
|
|
1800
|
+
continue;
|
|
1801
|
+
}
|
|
1802
|
+
|
|
1803
|
+
if (match("ArrayEnd")) {
|
|
1804
|
+
rows.push(currentRow);
|
|
1805
|
+
break;
|
|
1806
|
+
}
|
|
1807
|
+
|
|
1808
|
+
throw new Error(`Expected ',', ';', or ']' at ${current}`);
|
|
1809
|
+
}
|
|
1810
|
+
}
|
|
1811
|
+
|
|
1812
|
+
if (!rows.length) {
|
|
1813
|
+
return { type: "ArrayExpression", elements: [] };
|
|
1814
|
+
}
|
|
1815
|
+
|
|
1816
|
+
if (rows.length === 1) {
|
|
1817
|
+
return { type: "ArrayExpression", elements: rows[0] };
|
|
1818
|
+
}
|
|
1819
|
+
|
|
1820
|
+
return {
|
|
1821
|
+
type: "ArrayExpression",
|
|
1822
|
+
elements: rows.map((elements) => ({
|
|
1823
|
+
type: "ArrayExpression",
|
|
1824
|
+
elements
|
|
1825
|
+
}))
|
|
1826
|
+
};
|
|
1827
|
+
}
|
|
1828
|
+
|
|
1829
|
+
case "BlockStart": {
|
|
1830
|
+
const properties = [];
|
|
1831
|
+
|
|
1832
|
+
if (!match("BlockEnd")) {
|
|
1833
|
+
do {
|
|
1834
|
+
const keyToken = consume();
|
|
1835
|
+
|
|
1836
|
+
if (
|
|
1837
|
+
keyToken.type !== "Identifier" &&
|
|
1838
|
+
keyToken.type !== "String"
|
|
1839
|
+
) {
|
|
1840
|
+
throw new Error("Invalid object key");
|
|
1841
|
+
}
|
|
1842
|
+
|
|
1843
|
+
if (!match("Colon")) {
|
|
1844
|
+
throw new Error("Expected ':' after key");
|
|
1845
|
+
}
|
|
1846
|
+
|
|
1847
|
+
const value = parseExpression();
|
|
1848
|
+
|
|
1849
|
+
properties.push({
|
|
1850
|
+
key: keyToken.value,
|
|
1851
|
+
value
|
|
1852
|
+
});
|
|
1853
|
+
|
|
1854
|
+
} while (match("Comma"));
|
|
1855
|
+
|
|
1856
|
+
if (!match("BlockEnd")) {
|
|
1857
|
+
throw new Error(`Expected '}' at ${current}`);
|
|
1858
|
+
}
|
|
1859
|
+
}
|
|
1860
|
+
|
|
1861
|
+
return { type: "ObjectExpression", properties };
|
|
1862
|
+
}
|
|
1863
|
+
}
|
|
1864
|
+
|
|
1865
|
+
throw new Error(`Unexpected token: ${JSON.stringify(token)}`);
|
|
1866
|
+
}
|
|
1867
|
+
|
|
1868
|
+
/* ================= MEMBER ================= */
|
|
1869
|
+
function parseMember() {
|
|
1870
|
+
let object = parsePrimary();
|
|
1871
|
+
|
|
1872
|
+
while (true) {
|
|
1873
|
+
if (match("ArrayStart")) {
|
|
1874
|
+
const selectors = [];
|
|
1875
|
+
|
|
1876
|
+
if (!match("ArrayEnd")) {
|
|
1877
|
+
do {
|
|
1878
|
+
selectors.push(parseSliceOrIndex());
|
|
1879
|
+
} while (match("Comma"));
|
|
1880
|
+
|
|
1881
|
+
if (!match("ArrayEnd")) {
|
|
1882
|
+
throw new Error(`Expected ']' at ${current}`);
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
|
|
1886
|
+
object = {
|
|
1887
|
+
type: "IndexExpression",
|
|
1888
|
+
object,
|
|
1889
|
+
selectors
|
|
1890
|
+
};
|
|
1891
|
+
continue;
|
|
1892
|
+
}
|
|
1893
|
+
|
|
1894
|
+
if (match("Dot")) {
|
|
1895
|
+
const property = consume();
|
|
1896
|
+
|
|
1897
|
+
if (property.type !== "Identifier") {
|
|
1898
|
+
throw new Error("Expected property after '.'");
|
|
1899
|
+
}
|
|
1900
|
+
|
|
1901
|
+
object = {
|
|
1902
|
+
type: "MemberExpression",
|
|
1903
|
+
object,
|
|
1904
|
+
property: { type: "Identifier", name: property.value },
|
|
1905
|
+
optional: false
|
|
1906
|
+
};
|
|
1907
|
+
continue;
|
|
1908
|
+
}
|
|
1909
|
+
|
|
1910
|
+
if (match("Operator", "?.")) {
|
|
1911
|
+
const property = consume();
|
|
1912
|
+
|
|
1913
|
+
object = {
|
|
1914
|
+
type: "MemberExpression",
|
|
1915
|
+
object,
|
|
1916
|
+
property: { type: "Identifier", name: property.value },
|
|
1917
|
+
optional: true
|
|
1918
|
+
};
|
|
1919
|
+
continue;
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
break;
|
|
1923
|
+
}
|
|
1924
|
+
|
|
1925
|
+
return object;
|
|
1926
|
+
}
|
|
1927
|
+
|
|
1928
|
+
/* ================= CALL ================= */
|
|
1929
|
+
function parseCallChain() {
|
|
1930
|
+
let expr = parseMember();
|
|
1931
|
+
|
|
1932
|
+
while (peek()?.type === "Parenthesis" && peek()?.value === "(") {
|
|
1933
|
+
consume(); // '('
|
|
1934
|
+
|
|
1935
|
+
const args = [];
|
|
1936
|
+
|
|
1937
|
+
if (!(peek()?.type === "Parenthesis" && peek()?.value === ")")) {
|
|
1938
|
+
do {
|
|
1939
|
+
args.push(parseExpression());
|
|
1940
|
+
} while (match("Comma"));
|
|
1941
|
+
}
|
|
1942
|
+
|
|
1943
|
+
if (!match("Parenthesis", ")")) {
|
|
1944
|
+
throw new Error(`Expected ')' at ${current}`);
|
|
1945
|
+
}
|
|
1946
|
+
|
|
1947
|
+
expr = {
|
|
1948
|
+
type: "CallExpression",
|
|
1949
|
+
callee: expr,
|
|
1950
|
+
arguments: args
|
|
1951
|
+
};
|
|
1952
|
+
}
|
|
1953
|
+
|
|
1954
|
+
return expr;
|
|
1955
|
+
}
|
|
1956
|
+
|
|
1957
|
+
/* ================= UNARY ================= */
|
|
1958
|
+
function parseUnary() {
|
|
1959
|
+
if (match("UnaryOperator")) {
|
|
1960
|
+
const operator = tokens[current - 1].value;
|
|
1961
|
+
|
|
1962
|
+
return {
|
|
1963
|
+
type: "UnaryExpression",
|
|
1964
|
+
operator,
|
|
1965
|
+
argument: parseUnary()
|
|
1966
|
+
};
|
|
1967
|
+
}
|
|
1968
|
+
|
|
1969
|
+
return parseCallChain();
|
|
1970
|
+
}
|
|
1971
|
+
|
|
1972
|
+
/* ================= POWER ================= */
|
|
1973
|
+
function parsePower() {
|
|
1974
|
+
let left = parseUnary();
|
|
1975
|
+
|
|
1976
|
+
if (match("Operator", "^")) {
|
|
1977
|
+
const right = parsePower();
|
|
1978
|
+
return {
|
|
1979
|
+
type: "BinaryExpression",
|
|
1980
|
+
operator: "^",
|
|
1981
|
+
left,
|
|
1982
|
+
right
|
|
1983
|
+
};
|
|
1984
|
+
}
|
|
1985
|
+
|
|
1986
|
+
return left;
|
|
1987
|
+
}
|
|
1988
|
+
|
|
1989
|
+
/* ================= MULT ================= */
|
|
1990
|
+
function parseMultiplication() {
|
|
1991
|
+
let left = parsePower();
|
|
1992
|
+
|
|
1993
|
+
while (
|
|
1994
|
+
match("Operator", "*") ||
|
|
1995
|
+
match("Operator", "/") ||
|
|
1996
|
+
match("Operator", "%")
|
|
1997
|
+
) {
|
|
1998
|
+
const operator = tokens[current - 1].value;
|
|
1999
|
+
const right = parsePower();
|
|
2000
|
+
|
|
2001
|
+
left = {
|
|
2002
|
+
type: "BinaryExpression",
|
|
2003
|
+
operator,
|
|
2004
|
+
left,
|
|
2005
|
+
right
|
|
2006
|
+
};
|
|
2007
|
+
}
|
|
2008
|
+
|
|
2009
|
+
return left;
|
|
2010
|
+
}
|
|
2011
|
+
|
|
2012
|
+
/* ================= ADD ================= */
|
|
2013
|
+
function parseAddition() {
|
|
2014
|
+
let left = parseMultiplication();
|
|
2015
|
+
|
|
2016
|
+
while (match("Operator", "+") || match("Operator", "-")) {
|
|
2017
|
+
const operator = tokens[current - 1].value;
|
|
2018
|
+
const right = parseMultiplication();
|
|
2019
|
+
|
|
2020
|
+
left = {
|
|
2021
|
+
type: "BinaryExpression",
|
|
2022
|
+
operator,
|
|
2023
|
+
left,
|
|
2024
|
+
right
|
|
2025
|
+
};
|
|
2026
|
+
}
|
|
2027
|
+
|
|
2028
|
+
return left;
|
|
2029
|
+
}
|
|
2030
|
+
|
|
2031
|
+
/* ================= UNIT CONVERSION ================= */
|
|
2032
|
+
function parseUnitConversion() {
|
|
2033
|
+
let left = parseAddition();
|
|
2034
|
+
|
|
2035
|
+
const nextKeyword = peek();
|
|
2036
|
+
if (nextKeyword?.type === "Keyword" && ["to", "in"].includes(nextKeyword.value)) {
|
|
2037
|
+
consume();
|
|
2038
|
+
const next = consume();
|
|
2039
|
+
|
|
2040
|
+
if (!next || next.type !== "Unit") {
|
|
2041
|
+
throw new Error(`Expected unit after '${nextKeyword.value}'`);
|
|
2042
|
+
}
|
|
2043
|
+
|
|
2044
|
+
return {
|
|
2045
|
+
type: "UnitConversion",
|
|
2046
|
+
from: left,
|
|
2047
|
+
to: next.value
|
|
2048
|
+
};
|
|
2049
|
+
}
|
|
2050
|
+
|
|
2051
|
+
return left;
|
|
2052
|
+
}
|
|
2053
|
+
|
|
2054
|
+
/* ================= COMPARISON ================= */
|
|
2055
|
+
function parseComparison() {
|
|
2056
|
+
let left = parseUnitConversion();
|
|
2057
|
+
|
|
2058
|
+
while (
|
|
2059
|
+
match("Operator", ">") ||
|
|
2060
|
+
match("Operator", "<") ||
|
|
2061
|
+
match("Operator", ">=") ||
|
|
2062
|
+
match("Operator", "<=") ||
|
|
2063
|
+
match("Operator", "==")
|
|
2064
|
+
) {
|
|
2065
|
+
const operator = tokens[current - 1].value;
|
|
2066
|
+
const right = parseUnitConversion();
|
|
2067
|
+
|
|
2068
|
+
left = {
|
|
2069
|
+
type: "BinaryExpression",
|
|
2070
|
+
operator,
|
|
2071
|
+
left,
|
|
2072
|
+
right
|
|
2073
|
+
};
|
|
2074
|
+
}
|
|
2075
|
+
|
|
2076
|
+
return left;
|
|
2077
|
+
}
|
|
2078
|
+
|
|
2079
|
+
/* ================= LOGICAL ================= */
|
|
2080
|
+
function parseLogical() {
|
|
2081
|
+
let left = parseComparison();
|
|
2082
|
+
|
|
2083
|
+
while (
|
|
2084
|
+
match("Operator", "&&") ||
|
|
2085
|
+
match("Operator", "||")
|
|
2086
|
+
) {
|
|
2087
|
+
const operator = tokens[current - 1].value;
|
|
2088
|
+
const right = parseComparison();
|
|
2089
|
+
|
|
2090
|
+
left = {
|
|
2091
|
+
type: "LogicalExpression",
|
|
2092
|
+
operator,
|
|
2093
|
+
left,
|
|
2094
|
+
right
|
|
2095
|
+
};
|
|
2096
|
+
}
|
|
2097
|
+
|
|
2098
|
+
return left;
|
|
2099
|
+
}
|
|
2100
|
+
|
|
2101
|
+
/* ================= NULLISH ================= */
|
|
2102
|
+
function parseNullish() {
|
|
2103
|
+
let left = parseLogical();
|
|
2104
|
+
|
|
2105
|
+
while (match("Operator", "??")) {
|
|
2106
|
+
const right = parseLogical();
|
|
2107
|
+
|
|
2108
|
+
left = {
|
|
2109
|
+
type: "LogicalExpression",
|
|
2110
|
+
operator: "??",
|
|
2111
|
+
left,
|
|
2112
|
+
right
|
|
2113
|
+
};
|
|
2114
|
+
}
|
|
2115
|
+
|
|
2116
|
+
return left;
|
|
2117
|
+
}
|
|
2118
|
+
|
|
2119
|
+
/* ================= TERNARY ================= */
|
|
2120
|
+
function parseTernary() {
|
|
2121
|
+
let test = parseNullish();
|
|
2122
|
+
|
|
2123
|
+
if (match("Ternary", "?")) {
|
|
2124
|
+
const consequent = parseExpression();
|
|
2125
|
+
|
|
2126
|
+
if (!match("Ternary", ":")) {
|
|
2127
|
+
throw new Error("Expected ':' in ternary");
|
|
2128
|
+
}
|
|
2129
|
+
|
|
2130
|
+
const alternate = parseExpression();
|
|
2131
|
+
|
|
2132
|
+
return {
|
|
2133
|
+
type: "ConditionalExpression",
|
|
2134
|
+
test,
|
|
2135
|
+
consequent,
|
|
2136
|
+
alternate
|
|
2137
|
+
};
|
|
2138
|
+
}
|
|
2139
|
+
|
|
2140
|
+
return test;
|
|
2141
|
+
}
|
|
2142
|
+
|
|
2143
|
+
/* ================= PIPELINE ================= */
|
|
2144
|
+
function parsePipeline() {
|
|
2145
|
+
let left = parseTernary();
|
|
2146
|
+
|
|
2147
|
+
while (match("Operator", "|>")) {
|
|
2148
|
+
const right = parseTernary();
|
|
2149
|
+
|
|
2150
|
+
left = {
|
|
2151
|
+
type: "PipelineExpression",
|
|
2152
|
+
left,
|
|
2153
|
+
right
|
|
2154
|
+
};
|
|
2155
|
+
}
|
|
2156
|
+
|
|
2157
|
+
return left;
|
|
2158
|
+
}
|
|
2159
|
+
|
|
2160
|
+
/* ================= ASSIGNMENT ================= */
|
|
2161
|
+
function parseAssignment() {
|
|
2162
|
+
let left = parsePipeline();
|
|
2163
|
+
|
|
2164
|
+
if (
|
|
2165
|
+
match("Operator", "=") ||
|
|
2166
|
+
match("Operator", "+=") ||
|
|
2167
|
+
match("Operator", "-=") ||
|
|
2168
|
+
match("Operator", "*=") ||
|
|
2169
|
+
match("Operator", "/=")
|
|
2170
|
+
) {
|
|
2171
|
+
const operator = tokens[current - 1].value;
|
|
2172
|
+
|
|
2173
|
+
if (
|
|
2174
|
+
left.type !== "Identifier" &&
|
|
2175
|
+
left.type !== "MemberExpression" &&
|
|
2176
|
+
left.type !== "IndexExpression"
|
|
2177
|
+
) {
|
|
2178
|
+
throw new Error("Invalid assignment target");
|
|
2179
|
+
}
|
|
2180
|
+
|
|
2181
|
+
const right = parseAssignment();
|
|
2182
|
+
|
|
2183
|
+
return {
|
|
2184
|
+
type: "AssignmentExpression",
|
|
2185
|
+
operator,
|
|
2186
|
+
left,
|
|
2187
|
+
right
|
|
2188
|
+
};
|
|
2189
|
+
}
|
|
2190
|
+
|
|
2191
|
+
return left;
|
|
2192
|
+
}
|
|
2193
|
+
|
|
2194
|
+
/* ================= ENTRY ================= */
|
|
2195
|
+
function parseExpression() {
|
|
2196
|
+
return parseAssignment();
|
|
2197
|
+
}
|
|
2198
|
+
|
|
2199
|
+
const ast = parseExpression();
|
|
2200
|
+
|
|
2201
|
+
if (current < tokens.length) {
|
|
2202
|
+
throw new Error(
|
|
2203
|
+
`Unexpected token at end: ${JSON.stringify(peek())}`
|
|
2204
|
+
);
|
|
2205
|
+
}
|
|
2206
|
+
|
|
2207
|
+
return ast;
|
|
452
2208
|
}
|
|
453
2209
|
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
2210
|
+
//
|
|
2211
|
+
|
|
2212
|
+
const isComplex = (value) =>
|
|
2213
|
+
value && typeof value === "object" && "re" in value && "im" in value;
|
|
2214
|
+
|
|
2215
|
+
const isUnitValue = (value) =>
|
|
2216
|
+
value && typeof value === "object" && "value" in value && "unit" in value;
|
|
2217
|
+
|
|
2218
|
+
const isMatrix = (value) =>
|
|
2219
|
+
Array.isArray(value) && value.length > 0 && value.every(Array.isArray);
|
|
2220
|
+
|
|
2221
|
+
const formatComplex = (value) => {
|
|
2222
|
+
if (!isComplex(value)) return value;
|
|
2223
|
+
|
|
2224
|
+
const real = value.re;
|
|
2225
|
+
const imaginary = Math.abs(value.im);
|
|
2226
|
+
const sign = value.im < 0 ? "-" : "+";
|
|
2227
|
+
|
|
2228
|
+
if (real === 0) {
|
|
2229
|
+
if (value.im === 1) return "i";
|
|
2230
|
+
if (value.im === -1) return "-i";
|
|
2231
|
+
return `${value.im}i`;
|
|
2232
|
+
}
|
|
2233
|
+
|
|
2234
|
+
const imagPart = imaginary === 1 ? "i" : `${imaginary}i`;
|
|
2235
|
+
return `${real} ${sign} ${imagPart}`;
|
|
2236
|
+
};
|
|
2237
|
+
|
|
2238
|
+
const formatResult = (value) => {
|
|
2239
|
+
if (isComplex(value)) {
|
|
2240
|
+
return formatComplex(value);
|
|
2241
|
+
}
|
|
2242
|
+
|
|
2243
|
+
if (isUnitValue(value)) {
|
|
2244
|
+
return `${value.value} ${value.unit}`;
|
|
2245
|
+
}
|
|
2246
|
+
|
|
2247
|
+
if (isMatrix(value)) {
|
|
2248
|
+
return value.map((row) => row.join("\t")).join("\n");
|
|
2249
|
+
}
|
|
2250
|
+
|
|
2251
|
+
if (Array.isArray(value)) {
|
|
2252
|
+
return value.join("\n");
|
|
2253
|
+
}
|
|
2254
|
+
|
|
2255
|
+
return value;
|
|
2256
|
+
};
|
|
2257
|
+
|
|
2258
|
+
class exprify {
|
|
2259
|
+
constructor() {
|
|
2260
|
+
// Shared state
|
|
2261
|
+
this.math = mathOperations;
|
|
2262
|
+
this.units = createUnitsStore(globalUnits);
|
|
2263
|
+
this.functions = createFunctionRegistry(internalFunctions);
|
|
2264
|
+
this.variables = createVarStore();
|
|
2265
|
+
this._cache = new Map();
|
|
2266
|
+
}
|
|
2267
|
+
|
|
2268
|
+
setVariable(name, value) {
|
|
2269
|
+
this.variables.set(name, value);
|
|
2270
|
+
}
|
|
2271
|
+
|
|
2272
|
+
getVariable(name) {
|
|
2273
|
+
return this.variables.get(name);
|
|
2274
|
+
}
|
|
2275
|
+
|
|
2276
|
+
addFunction(name, fn) {
|
|
2277
|
+
this.functions.register(name, fn);
|
|
2278
|
+
}
|
|
2279
|
+
|
|
2280
|
+
_createContext() {
|
|
2281
|
+
return createContext({
|
|
2282
|
+
functions: this.functions,
|
|
2283
|
+
variables: this.variables,
|
|
2284
|
+
units: this.units,
|
|
2285
|
+
evaluate: this.evaluate.bind(this)
|
|
2286
|
+
});
|
|
2287
|
+
}
|
|
2288
|
+
|
|
2289
|
+
tokenize(expr) {
|
|
2290
|
+
if (typeof expr !== "string") {
|
|
2291
|
+
throw new Error("Expression must be a string");
|
|
2292
|
+
}
|
|
2293
|
+
return tokenize(expr, this._createContext());
|
|
2294
|
+
}
|
|
2295
|
+
|
|
2296
|
+
parse(expr) {
|
|
2297
|
+
const tokens = this.tokenize(expr);
|
|
2298
|
+
const ast = buildAST(tokens);
|
|
2299
|
+
return { tokens, ast };
|
|
2300
|
+
}
|
|
2301
|
+
|
|
2302
|
+
evaluate(expr) {
|
|
2303
|
+
const { ast } = this.parse(expr);
|
|
2304
|
+
return formatResult(evaluateAST(
|
|
2305
|
+
ast,
|
|
2306
|
+
this._createContext()
|
|
2307
|
+
));
|
|
2308
|
+
}
|
|
2309
|
+
|
|
2310
|
+
compile(expr) {
|
|
2311
|
+
if (this._cache.has(expr)) {
|
|
2312
|
+
return this._cache.get(expr);
|
|
2313
|
+
}
|
|
2314
|
+
|
|
2315
|
+
const { ast } = this.parse(expr);
|
|
2316
|
+
|
|
2317
|
+
const compiledFn = (scope = {}) => {
|
|
2318
|
+
const baseContext = this._createContext();
|
|
2319
|
+
const scopedContext = baseContext.withScope(scope);
|
|
2320
|
+
return formatResult(evaluateAST(ast, scopedContext));
|
|
2321
|
+
};
|
|
2322
|
+
|
|
2323
|
+
this._cache.set(expr, compiledFn);
|
|
2324
|
+
return compiledFn;
|
|
2325
|
+
}
|
|
2326
|
+
|
|
2327
|
+
clearCache() {
|
|
2328
|
+
this._cache.clear();
|
|
2329
|
+
}
|
|
2330
|
+
|
|
508
2331
|
}
|
|
509
2332
|
|
|
510
|
-
export {
|
|
2333
|
+
export { exprify as default };
|
|
511
2334
|
|