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