exprify 1.0.0 → 1.0.2

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,511 +1,3001 @@
1
- function tokenize(expr, context) {
2
- let tokens = [];
3
- let current = "";
4
- let quote = "";
5
-
6
- for (let i = 0; i < expr.length; i++) {
7
-
8
- let char = expr[i];
9
-
10
- const isOperator =
11
- char === '(' || char === ')' ||
12
- char === '^' || char === '*' ||
13
- char === '/' || char === '%' ||
14
- char === '+' || char === '-';
15
-
16
- const isQuote = char === '"' || char === "'" || char === "`";
17
-
18
- if (isQuote) {
19
- if (quote === "") {
20
- quote = char;
21
- current += char;
22
- } else if (quote === char) {
23
- current += char;
24
- quote = "";
25
-
26
- tokens.push(context.stringToJS(current, context.variablesDB));
27
- current = "";
28
- } else {
29
- current += char;
30
- }
31
- continue;
32
- }
33
-
34
- if (quote !== "") {
35
- current += char;
36
- continue;
37
- }
38
-
39
- if (char === "#") {
40
-
41
- let bracket = 0;
42
- let funcName = "";
43
- let arg = "";
44
- let args = [];
45
- let quoteFunc = "";
46
-
47
- while (i < expr.length - 1) {
48
- i++;
49
- char = expr[i];
50
-
51
- if (bracket === 0) {
52
- if (char === "(") {
53
- bracket++;
54
- continue;
55
- }
56
-
57
- if (char === " ")
58
- throw new Error("Function name cannot contain space");
59
-
60
- if (isQuote)
61
- throw new Error("Function name cannot contain quotes");
62
-
63
- if (funcName === "" && /[0-9.]/.test(char))
64
- throw new Error("Function name cannot start with number");
65
-
66
- funcName += char;
67
- continue;
68
- }
69
-
70
- if (isQuote) {
71
- if (quoteFunc === "") quoteFunc = char;
72
- else if (quoteFunc === char) quoteFunc = "";
73
- }
74
-
75
- if (quoteFunc === "") {
76
-
77
- if (char === "(") bracket++;
78
- else if (char === ")") {
79
- bracket--;
80
-
81
- if (bracket === 0) {
82
- if (arg !== "") args.push(arg);
83
- break;
84
- }
85
- }
86
-
87
- if (char === "," && bracket === 1) {
88
- if (arg === "")
89
- throw new Error(`Missing argument in #${funcName}()`);
90
-
91
- args.push(arg);
92
- arg = "";
93
- continue;
94
- }
95
- }
96
-
97
- arg += char;
98
- }
99
-
100
- args = args.map(a => context.evaluate(a));
101
-
102
- let fn =
103
- context.func_DB_intrnl[funcName] ||
104
- context.func_DB_extrnl[funcName];
105
-
106
- if (!fn) {
107
- throw new Error(`#${funcName}() not defined`);
108
- }
109
-
110
- tokens.push(fn(...args));
111
- continue;
112
- }
113
-
114
- if (isOperator) {
115
-
116
- if (current !== "") {
117
- tokens.push(context.stringToJS(current, context.variablesDB));
118
- current = "";
119
- }
120
-
121
- tokens.push(char);
122
- continue;
123
- }
124
-
125
- if (char === " ") {
126
- if (current !== "") {
127
- tokens.push(context.stringToJS(current, context.variablesDB));
128
- current = "";
129
- }
130
- continue;
131
- }
132
-
133
- current += char;
134
-
135
- if (i === expr.length - 1 && current !== "") {
136
- tokens.push(context.stringToJS(current, context.variablesDB));
137
- }
138
- }
139
-
140
- if (quote !== "") {
141
- throw new Error("Unclosed string literal");
142
- }
143
-
144
- return tokens;
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 infixToPostfix(tokens, operator_precedence) {
148
- let output = [];
149
- let stack = [];
150
-
151
- for (let i = 0; i < tokens.length; i++) {
152
-
153
- let token = tokens[i];
154
-
155
- const isOperator =
156
- token === '^' || token === '*' ||
157
- token === '/' || token === '%' ||
158
- token === '+' || token === '-';
159
-
160
- const isLeftParen = token === "(";
161
- const isRightParen = token === ")";
162
-
163
- const isOperand = !isOperator && !isLeftParen && !isRightParen;
164
-
165
- if (isOperand) {
166
- output.push(token);
167
- }
168
-
169
- else if (isOperator) {
170
-
171
- while (stack.length > 0) {
172
-
173
- let top = stack[stack.length - 1];
174
-
175
- if (top === "(") break;
176
-
177
- let topPrec = operator_precedence[top] || 0;
178
- let currPrec = operator_precedence[token];
179
-
180
- // Right associativity for ^
181
- if (
182
- (token === '^' && currPrec < topPrec) ||
183
- (token !== '^' && currPrec <= topPrec)
184
- ) {
185
- output.push(stack.pop());
186
- } else {
187
- break;
188
- }
189
- }
190
-
191
- stack.push(token);
192
- }
193
-
194
- else if (isLeftParen) {
195
- stack.push(token);
196
- }
197
-
198
- else if (isRightParen) {
199
-
200
- while (stack.length > 0 && stack[stack.length - 1] !== "(") {
201
- output.push(stack.pop());
202
- }
203
-
204
- if (stack.length === 0) {
205
- throw new Error("Mismatched parentheses: missing '('");
206
- }
207
-
208
- stack.pop();
209
- }
210
- }
211
-
212
- while (stack.length > 0) {
213
-
214
- let top = stack.pop();
215
-
216
- if (top === "(" || top === ")") {
217
- throw new Error("Mismatched parentheses");
218
- }
219
-
220
- output.push(top);
221
- }
222
-
223
- return output;
401
+ const isDenseMatrixWrapper = (value) =>
402
+ value &&
403
+ typeof value === "object" &&
404
+ value.exprify === "DenseMatrix" &&
405
+ "data" in value &&
406
+ "size" in value;
407
+
408
+ const cloneMatrixData = (value) => {
409
+ if (Array.isArray(value)) {
410
+ return value.map(cloneMatrixData);
411
+ }
412
+
413
+ return value;
414
+ };
415
+
416
+ const getMatrixSize = (data) => {
417
+ if (Array.isArray(data) && data.every(Array.isArray)) {
418
+ return [data.length, data[0]?.length || 0];
419
+ }
420
+
421
+ if (Array.isArray(data)) {
422
+ return [data.length];
423
+ }
424
+
425
+ throw new Error("Matrix data must be an array");
426
+ };
427
+
428
+ const wrapDenseMatrix = (data) => ({
429
+ exprify: "DenseMatrix",
430
+ data: cloneMatrixData(data),
431
+ size: getMatrixSize(data)
432
+ });
433
+
434
+ const unwrapDenseMatrix = (value) =>
435
+ isDenseMatrixWrapper(value) ? cloneMatrixData(value.data) : value;
436
+
437
+ const serializeExprifyValue = (value) => {
438
+ if (isDenseMatrixWrapper(value)) {
439
+ return JSON.stringify(value);
440
+ }
441
+
442
+ if (Array.isArray(value) || (value && typeof value === "object")) {
443
+ return JSON.stringify(value, (_, current) => {
444
+ if (isDenseMatrixWrapper(current)) {
445
+ return current;
446
+ }
447
+
448
+ return current;
449
+ });
450
+ }
451
+
452
+ return value;
453
+ };
454
+
455
+ function evaluateAST(node, context = {}) {
456
+
457
+ const vars = context.variables;
458
+ const fns = context.functions;
459
+ const units = context.units;
460
+
461
+
462
+ const isUnitObj = (v) =>
463
+ v && typeof v === "object" && "value" in v && "unit" in v;
464
+
465
+ const isComplex = (v) =>
466
+ v && typeof v === "object" && "re" in v && "im" in v;
467
+
468
+ const isSliceNode = (v) =>
469
+ v && typeof v === "object" && v.type === "SliceExpression";
470
+
471
+ const isMatrix = (v) =>
472
+ Array.isArray(v) && v.length > 0 && v.every(Array.isArray);
473
+
474
+ const normalizeMatrix = (value) => {
475
+ value = unwrapDenseMatrix(value);
476
+ if (isMatrix(value)) return value.map((row) => [...row]);
477
+ if (Array.isArray(value)) return [value];
478
+ throw new Error("Expected matrix-compatible value");
479
+ };
480
+
481
+ const toOneBasedIndex = (value) => {
482
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
483
+ throw new Error("Matrix indices must be positive integers");
484
+ }
485
+
486
+ return value - 1;
487
+ };
488
+
489
+ const resolveSelector = (selector, contextLength) => {
490
+ if (isSliceNode(selector)) {
491
+ const startValue = selector.start == null ? 1 : evaluateAST(selector.start, context);
492
+ const endValue = selector.end == null ? contextLength : evaluateAST(selector.end, context);
493
+ const start = toOneBasedIndex(startValue);
494
+ const end = toOneBasedIndex(endValue);
495
+
496
+ if (end < start) {
497
+ return [];
498
+ }
499
+
500
+ const result = [];
501
+ for (let index = start; index <= end; index++) {
502
+ result.push(index);
503
+ }
504
+ return result;
505
+ }
506
+
507
+ return [toOneBasedIndex(evaluateAST(selector, context))];
508
+ };
509
+
510
+ const indexMatrix = (matrix, selectors) => {
511
+ const target = normalizeMatrix(matrix);
512
+
513
+ if (selectors.length === 1) {
514
+ const rowIndexes = resolveSelector(selectors[0], target.length);
515
+ const rows = rowIndexes.map((rowIndex) => {
516
+ if (rowIndex >= target.length) {
517
+ throw new Error("Row index out of range");
518
+ }
519
+ return [...target[rowIndex]];
520
+ });
521
+
522
+ return rows.length === 1 ? rows[0] : rows;
523
+ }
524
+
525
+ const rowIndexes = resolveSelector(selectors[0], target.length);
526
+ const colIndexes = resolveSelector(selectors[1], target[0]?.length || 0);
527
+
528
+ const values = rowIndexes.map((rowIndex) => {
529
+ if (rowIndex >= target.length) {
530
+ throw new Error("Row index out of range");
531
+ }
532
+
533
+ return colIndexes.map((colIndex) => {
534
+ if (colIndex >= target[rowIndex].length) {
535
+ throw new Error("Column index out of range");
536
+ }
537
+ return target[rowIndex][colIndex];
538
+ });
539
+ });
540
+
541
+ if (rowIndexes.length === 1 && colIndexes.length === 1) {
542
+ return values[0][0];
543
+ }
544
+
545
+ if (rowIndexes.length === 1) {
546
+ return values[0];
547
+ }
548
+
549
+ if (colIndexes.length === 1) {
550
+ return values.map((row) => [row[0]]);
551
+ }
552
+
553
+ return values;
554
+ };
555
+
556
+ const assignMatrixIndex = (matrix, selectors, value) => {
557
+ const target = isMatrix(matrix)
558
+ ? matrix.map((row) => [...row])
559
+ : Array.isArray(matrix)
560
+ ? [matrix.slice()]
561
+ : [];
562
+
563
+ const rowSelector = selectors[0];
564
+ const colSelector = selectors[1];
565
+
566
+ if (!rowSelector) {
567
+ throw new Error("Matrix assignment requires at least one index");
568
+ }
569
+
570
+ const rowContextLength = Math.max(target.length, 1);
571
+ const rowIndexes = resolveSelector(rowSelector, rowContextLength);
572
+
573
+ if (selectors.length === 1) {
574
+ const rowsValue = isMatrix(value) ? value : normalizeMatrix(value);
575
+
576
+ if (rowsValue.length !== rowIndexes.length) {
577
+ throw new Error("Assigned row count does not match slice");
578
+ }
579
+
580
+ rowIndexes.forEach((rowIndex, index) => {
581
+ target[rowIndex] = [...rowsValue[index]];
582
+ });
583
+
584
+ return {
585
+ updatedMatrix: target,
586
+ selectionResult: rowIndexes.length === 1 ? [target[rowIndexes[0]]] : rowIndexes.map((rowIndex) => [target[rowIndex]])
587
+ };
588
+ }
589
+
590
+ const maxCols = Math.max(...target.map((row) => row.length), 0, 1);
591
+ const colIndexes = resolveSelector(colSelector, maxCols);
592
+ const normalizedValue = normalizeMatrix(value);
593
+
594
+ if (normalizedValue.length !== rowIndexes.length) {
595
+ throw new Error("Assigned row count does not match matrix slice");
596
+ }
597
+
598
+ normalizedValue.forEach((row, rowOffset) => {
599
+ if (row.length !== colIndexes.length) {
600
+ throw new Error("Assigned column count does not match matrix slice");
601
+ }
602
+ });
603
+
604
+ rowIndexes.forEach((rowIndex, rowOffset) => {
605
+ if (!target[rowIndex]) {
606
+ target[rowIndex] = [];
607
+ }
608
+
609
+ colIndexes.forEach((colIndex, colOffset) => {
610
+ target[rowIndex][colIndex] = normalizedValue[rowOffset][colOffset];
611
+ });
612
+ });
613
+
614
+ return {
615
+ updatedMatrix: target,
616
+ selectionResult: rowIndexes.length === 1
617
+ ? [colIndexes.map((colIndex) => target[rowIndexes[0]][colIndex])]
618
+ : rowIndexes.map((rowIndex) => colIndexes.map((colIndex) => target[rowIndex][colIndex]))
619
+ };
620
+ };
621
+
622
+ const multiplyMatrices = (left, right) => {
623
+ const a = normalizeMatrix(left);
624
+ const b = normalizeMatrix(right);
625
+
626
+ if (a[0].length !== b.length) {
627
+ throw new Error("Matrix dimensions do not allow multiplication");
628
+ }
629
+
630
+ return a.map((row) =>
631
+ b[0].map((_, colIndex) =>
632
+ row.reduce((sum, value, rowIndex) => sum + (value * b[rowIndex][colIndex]), 0)
633
+ )
634
+ );
635
+ };
636
+
637
+ const toComplex = (value) => {
638
+ if (isComplex(value)) return value;
639
+ if (typeof value === "number") return { re: value, im: 0 };
640
+ throw new Error("Complex arithmetic only supports numbers");
641
+ };
642
+
643
+ const fromImaginary = (value) => ({ re: 0, im: value });
644
+
645
+ const simplifyComplex = (value) =>
646
+ value.im === 0 ? value.re : value;
647
+
648
+ const createFunctionScope = (params, args) => {
649
+ const scopedValues = {};
650
+
651
+ params.forEach((param, index) => {
652
+ scopedValues[param] = args[index];
653
+ });
654
+
655
+ return scopedValues;
656
+ };
657
+
658
+ const evalComplexBinary = (operator, left, right) => {
659
+ const a = toComplex(left);
660
+ const b = toComplex(right);
661
+
662
+ switch (operator) {
663
+ case "+":
664
+ return simplifyComplex({ re: a.re + b.re, im: a.im + b.im });
665
+ case "-":
666
+ return simplifyComplex({ re: a.re - b.re, im: a.im - b.im });
667
+ case "*":
668
+ return simplifyComplex({
669
+ re: (a.re * b.re) - (a.im * b.im),
670
+ im: (a.re * b.im) + (a.im * b.re)
671
+ });
672
+ case "/": {
673
+ const denominator = (b.re ** 2) + (b.im ** 2);
674
+
675
+ if (denominator === 0) {
676
+ throw new Error("Division by zero");
677
+ }
678
+
679
+ return simplifyComplex({
680
+ re: ((a.re * b.re) + (a.im * b.im)) / denominator,
681
+ im: ((a.im * b.re) - (a.re * b.im)) / denominator
682
+ });
683
+ }
684
+ default:
685
+ throw new Error(`Operator ${operator} is not supported for complex numbers`);
686
+ }
687
+ };
688
+
689
+ /* ================= EVALUATOR ================= */
690
+
691
+ switch (node.type) {
692
+
693
+ /* ===== LITERAL ===== */
694
+ case "Literal":
695
+ return node.value;
696
+
697
+ case "ImaginaryLiteral":
698
+ return fromImaginary(node.value);
699
+
700
+ case "UnitLiteral":
701
+ return { value: node.value, unit: node.unit };
702
+
703
+ /* ===== VARIABLE ===== */
704
+ case "Identifier":
705
+ return vars.get(node.name);
706
+
707
+ /* ===== ASSIGNMENT ===== */
708
+ case "AssignmentExpression": {
709
+ const value = evaluateAST(node.right, context);
710
+
711
+ if (node.left.type === "Identifier") {
712
+ vars.set(node.left.name, value);
713
+ if (node.right.type === "ArrayExpression") {
714
+ return wrapDenseMatrix(unwrapDenseMatrix(value));
715
+ }
716
+ return value;
717
+ }
718
+
719
+ if (node.left.type === "IndexExpression" && node.left.object.type === "Identifier") {
720
+ const currentValue = vars.get(node.left.object.name);
721
+ const assigned = assignMatrixIndex(currentValue, node.left.selectors, value);
722
+ vars.set(node.left.object.name, assigned.updatedMatrix);
723
+ return assigned.selectionResult;
724
+ }
725
+
726
+ throw new Error("Invalid assignment target");
727
+ }
728
+
729
+ case "FunctionAssignmentExpression": {
730
+ if (node.operator !== "=") {
731
+ throw new Error(`Operator ${node.operator} is not supported for function definitions`);
732
+ }
733
+
734
+ const fn = (...args) => {
735
+ const scopedContext = context.withScope(createFunctionScope(node.params, args));
736
+ return evaluateAST(node.right, scopedContext);
737
+ };
738
+
739
+ fns.register(node.left.name, fn);
740
+ return fn;
741
+ }
742
+
743
+ /* ===== UNARY ===== */
744
+ case "UnaryExpression": {
745
+ const val = evaluateAST(node.argument, context);
746
+
747
+ switch (node.operator) {
748
+ case "-":
749
+ return isComplex(val)
750
+ ? simplifyComplex({ re: -val.re, im: -val.im })
751
+ : -val;
752
+ case "!": return !val;
753
+ }
754
+
755
+ throw new Error(`Unknown unary operator ${node.operator}`);
756
+ }
757
+
758
+ /* ===== BINARY ===== */
759
+ case "BinaryExpression": {
760
+ let left = evaluateAST(node.left, context);
761
+ let right = evaluateAST(node.right, context);
762
+
763
+ // UNIT handling
764
+ if (isUnitObj(left) || isUnitObj(right)) {
765
+
766
+ if (!units) throw new Error("Unit system not available");
767
+
768
+ return units.compute(node.operator, left, right);
769
+ }
770
+
771
+ if (node.operator === "*" && (Array.isArray(left) || Array.isArray(right))) {
772
+ return multiplyMatrices(left, right);
773
+ }
774
+
775
+ if (isComplex(left) || isComplex(right)) {
776
+ return evalComplexBinary(node.operator, left, right);
777
+ }
778
+
779
+ switch (node.operator) {
780
+ case "+": return left + right;
781
+ case "-": return left - right;
782
+ case "*": return left * right;
783
+ case "/": return left / right;
784
+ case "%": return left % right;
785
+ case "^": return left ** right;
786
+
787
+ case ">": return left > right;
788
+ case "<": return left < right;
789
+ case ">=": return left >= right;
790
+ case "<=": return left <= right;
791
+ case "==": return left === right;
792
+ }
793
+
794
+ throw new Error(`Unknown operator ${node.operator}`);
795
+ }
796
+
797
+ /* ===== LOGICAL ===== */
798
+ case "LogicalExpression": {
799
+ const left = evaluateAST(node.left, context);
800
+
801
+ if (node.operator === "&&") {
802
+ return left && evaluateAST(node.right, context);
803
+ }
804
+
805
+ if (node.operator === "||") {
806
+ return left || evaluateAST(node.right, context);
807
+ }
808
+
809
+ if (node.operator === "??") {
810
+ return left ?? evaluateAST(node.right, context);
811
+ }
812
+
813
+ throw new Error(`Unknown logical operator ${node.operator}`);
814
+ }
815
+
816
+ /* ===== FUNCTION CALL ===== */
817
+ case "CallExpression": {
818
+ const fnName = node.callee.name;
819
+ const fn = fns.get(fnName);
820
+
821
+ const args = node.arguments.map(arg =>
822
+ evaluateAST(arg, context)
823
+ );
824
+
825
+ return fn(...args);
826
+ }
827
+
828
+ /* ===== PIPELINE ===== */
829
+ case "PipelineExpression": {
830
+ const leftVal = evaluateAST(node.left, context);
831
+
832
+ // right must be function
833
+ if (node.right.type === "CallExpression") {
834
+ const fnName = node.right.callee.name;
835
+ const fn = fns.get(fnName);
836
+
837
+ const args = [
838
+ leftVal,
839
+ ...node.right.arguments.map(arg =>
840
+ evaluateAST(arg, context)
841
+ )
842
+ ];
843
+
844
+ return fn(...args);
845
+ }
846
+
847
+ if (node.right.type === "Identifier") {
848
+ const fn = fns.get(node.right.name);
849
+ return fn(leftVal);
850
+ }
851
+
852
+ throw new Error("Invalid pipeline target");
853
+ }
854
+
855
+ /* ===== UNIT CONVERSION ===== */
856
+ case "UnitConversion": {
857
+ const from = evaluateAST(node.from, context);
858
+
859
+ if (!isUnitObj(from)) {
860
+ throw new Error("Left side must be a unit value");
861
+ }
862
+
863
+ if (!units) {
864
+ throw new Error("Unit system not available");
865
+ }
866
+
867
+ return units.convert(from.value, from.unit, node.to);
868
+ }
869
+
870
+ /* ===== ARRAY ===== */
871
+ case "ArrayExpression":
872
+ return node.elements.map(el => evaluateAST(el, context));
873
+
874
+ case "IndexExpression": {
875
+ const target = evaluateAST(node.object, context);
876
+ return indexMatrix(target, node.selectors);
877
+ }
878
+
879
+ /* ===== OBJECT ===== */
880
+ case "ObjectExpression": {
881
+ const obj = {};
882
+ for (let p of node.properties) {
883
+ obj[p.key] = evaluateAST(p.value, context);
884
+ }
885
+ return obj;
886
+ }
887
+
888
+ /* ===== MEMBER ===== */
889
+ case "MemberExpression": {
890
+ const obj = evaluateAST(node.object, context);
891
+
892
+ if (node.optional && obj == null) return undefined;
893
+
894
+ return obj[node.property.name];
895
+ }
896
+
897
+ default:
898
+ throw new Error(`Unknown AST node type: ${node.type}`);
899
+ }
224
900
  }
225
901
 
226
- function evaluatePostfix(postfix, mathOperations) {
227
-
228
- let stack = [];
229
-
230
- const isOperator = (val) =>
231
- val === '^' || val === '*' ||
232
- val === '/' || val === '%' ||
233
- val === '+' || val === '-';
234
-
235
- for (let i = 0; i < postfix.length; i++) {
236
-
237
- let token = postfix[i];
238
-
239
- if (!isOperator(token)) {
240
- stack.push(token);
241
- continue;
242
- }
243
-
244
- if (stack.length < 2) {
245
- throw new Error("Invalid expression: insufficient operands");
246
- }
247
-
248
- let b = stack.pop(); // second
249
- let a = stack.pop(); // first
250
-
251
- let result;
252
-
253
- switch (token) {
254
- case '^':
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];
902
+ function createContext({ variables, functions, units, evaluate}) {
903
+ if (!variables) throw new Error("Variable store missing");
904
+ if (!functions) throw new Error("Function registry missing");
905
+ if (!units) throw new Error("Units list missing");
906
+ if (!evaluate) throw new Error("evaluate function missing");
907
+
908
+ return {
909
+ variables: variables,
910
+ functions: functions,
911
+ units: units,
912
+ evaluate,
913
+ withScope(scope = {}) {
914
+ const tempVars = {
915
+ ...variables.all?.(),
916
+ ...scope
917
+ };
918
+ return createContext({
919
+ functions: functions,
920
+ evaluate,
921
+ units,
922
+ variables: {
923
+ get: (k) => tempVars[k],
924
+ set: (k, v) => (tempVars[k] = v),
925
+ all: () => tempVars
926
+ }
927
+ });
928
+
929
+ }
930
+ };
282
931
  }
283
932
 
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
- operator_precedence: {
291
- '^': 4,
292
- '*': 3,
293
- '/': 3,
294
- '%': 3,
295
- '+': 1,
296
- '-': 1,
297
- },
298
-
299
- power: function(a, b) {
300
- if (isValidNumberPair(a, b)) return a ** b;
301
- throw new Error("Invalid types for ^");
302
- },
303
-
304
- multiply: function(a, b) {
305
- if (isValidNumberPair(a, b)) return a * b;
306
- throw new Error("Invalid types for *");
307
- },
308
-
309
- divide: function(a, b) {
310
- if (isValidNumberPair(a, b)) {
311
- if (b === 0) throw new Error("Division by zero");
312
- return a / b;
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
- });
933
+ const isValidNumberPair = (a, b) =>
934
+ (typeof a === typeof b) &&
935
+ (typeof a === 'number' || typeof a === 'bigint');
936
+
937
+ const mathOperations = Object.freeze({
938
+ power: function(a, b) {
939
+ if (isValidNumberPair(a, b)) return a ** b;
940
+ throw new Error("Invalid types for ^");
941
+ },
942
+
943
+ multiply: function(a, b) {
944
+ if (isValidNumberPair(a, b)) return a * b;
945
+ throw new Error("Invalid types for *");
946
+ },
947
+
948
+ divide: function(a, b) {
949
+ if (isValidNumberPair(a, b)) {
950
+ if (b === 0) throw new Error("Division by zero");
951
+ return a / b;
952
+ }
953
+ throw new Error("Invalid types for /");
954
+ },
955
+
956
+ add: function(a, b) {
957
+ if (isValidNumberPair(a, b)) return a + b;
958
+ if (typeof a === 'string' && typeof b === 'string') return a + b;
959
+ throw new Error("Invalid types for +");
960
+ },
961
+ subtract: function(a, b) {
962
+ if (isValidNumberPair(a, b)) return a - b;
963
+ throw new Error("Invalid types for -");
964
+ },
332
965
 
333
- const and = (...args) => args.every(Boolean);
334
- const or = (...args) => args.some(Boolean);
335
- const not = (val) => !val;
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
-
966
+ modulus: function(a, b) {
967
+ if (isValidNumberPair(a, b)) return a % b;
968
+ throw new Error("Invalid types for %");
969
+ }
385
970
  });
386
971
 
387
- const externalFunctions = {};
388
-
389
- const variablesDB = {};
390
-
391
- function stringToJS(str, variablesDB) {
392
- if (typeof str !== "string" || str.length === 0) {
393
- throw new Error("Invalid input: expected a non-empty string.");
394
- }
395
-
396
- const firstChar = str[0];
397
- const lastChar = str[str.length - 1];
398
-
399
- // HEX (0x...)
400
- if (/^0x[0-9a-fA-F]+n?$/.test(str)) {
401
-
402
- // BigInt hex (0xFFn)
403
- if (lastChar === 'n') {
404
- return BigInt(str.slice(0, -1));
405
- }
406
-
407
- return Number(str);
408
- }
409
-
410
- if (/^[+-]?(\d+(\.\d+)?|\.\d+)(e[+-]?\d+)?n?$/i.test(str)) {
411
-
412
- // BigInt
413
- if (lastChar === 'n') {
414
- const numPart = str.slice(0, -1);
415
-
416
- if (numPart.includes('.') || /e/i.test(numPart)) {
417
- throw new Error(`Invalid BigInt: ${str}`);
418
- }
419
-
420
- return BigInt(numPart);
421
- }
422
-
423
- return Number(str);
424
- }
425
-
426
- if (
427
- (firstChar === '"' && lastChar === '"') ||
428
- (firstChar === "'" && lastChar === "'") ||
429
- (firstChar === '`' && lastChar === '`')
430
- ) {
431
- return str.slice(1, -1);
432
- }
433
-
434
- if (
435
- firstChar === '"' ||
436
- firstChar === "'" ||
437
- firstChar === '`'
438
- ) {
439
- throw new Error(`Unmatched or missing quotes: ${str}`);
440
- }
441
-
442
- if (str === "true") return true;
443
- if (str === "false") return false;
444
-
445
- if (str in variablesDB) {
446
- return variablesDB[str];
447
- }
448
-
449
- throw new Error(
450
- `${str} is not defined. Use setVariable("${str}", value) first.`
451
- );
972
+ function createUnitsStore(initial = {}) {
973
+ let units = { ...initial};
974
+
975
+ // ---------- Helpers ----------
976
+
977
+ function getAllUnitsFlat() {
978
+ const result = new Set();
979
+
980
+ for (const type in units) {
981
+ for (const key in units[type]) {
982
+ const u = units[type][key];
983
+
984
+ const keyLower = key.toLowerCase();
985
+ result.add(keyLower);
986
+
987
+ // Unit name
988
+ if (u.unit) {
989
+ const unitLower = u.unit.toLowerCase();
990
+
991
+ // Avoid duplicate like "m" vs "meter"
992
+ if (unitLower !== keyLower) {
993
+ // Optional: only single-word units
994
+ if (unitLower.split(/\s+/).length === 1) {
995
+ result.add(unitLower);
996
+ }
997
+ }
998
+ }
999
+
1000
+ // Symbol
1001
+ if (u.symbol) {
1002
+ const symbolLower = u.symbol.toLowerCase();
1003
+
1004
+ // Avoid duplicate with unit name
1005
+ if (!u.unit || symbolLower !== u.unit.toLowerCase()) {
1006
+ result.add(symbolLower);
1007
+ }
1008
+ }
1009
+ }
1010
+ }
1011
+
1012
+ return Array.from(result);
1013
+ }
1014
+
1015
+ function findUnit(input) {
1016
+ input = input.toLowerCase();
1017
+
1018
+ for (const type in units) {
1019
+ for (const key in units[type]) {
1020
+ const u = units[type][key];
1021
+
1022
+ if (
1023
+ key.toLowerCase() === input ||
1024
+ u.unit?.toLowerCase() === input ||
1025
+ u.symbol?.toLowerCase() === input
1026
+ ) {
1027
+ return { type, key , data: u};
1028
+ }
1029
+ }
1030
+ }
1031
+
1032
+ return null;
1033
+ }
1034
+
1035
+ // ---------- Core Convert ----------
1036
+
1037
+ function convert(value, fromUnit, toUnit) {
1038
+ const from = findUnit(fromUnit);
1039
+ const to = findUnit(toUnit);
1040
+
1041
+ if (!from) throw new Error(`Unknown unit: ${fromUnit}`);
1042
+ if (!to) throw new Error(`Unknown unit: ${toUnit}`);
1043
+
1044
+ if (from.type !== to.type) {
1045
+ 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(", ")}`);
1046
+ }
1047
+
1048
+ const result = value * (from.data.value / to.data.value);
1049
+
1050
+ return { value: result, unit: to.key };
1051
+ }
1052
+
1053
+ // ---------- Public API ----------
1054
+
1055
+ return {
1056
+ // Get all units
1057
+ getUnits: () => units,
1058
+
1059
+ // Replace all units
1060
+ setUnits: (newUnits) => {
1061
+ units = { ...newUnits };
1062
+ },
1063
+
1064
+ // Update single type
1065
+ updateType: (type, data) => {
1066
+ units[type] = { ...units[type], ...data };
1067
+ },
1068
+
1069
+ // Add new unit
1070
+ addUnit: (type, key, unitObj) => {
1071
+ if (!units[type]) units[type] = {};
1072
+ units[type][key] = unitObj;
1073
+ },
1074
+ compute(op, left, right) {
1075
+
1076
+ const isUnit = (v) =>
1077
+ v && typeof v === "object" && "value" in v && "unit" in v;
1078
+
1079
+ const apply = (a, b) => {
1080
+ switch (op) {
1081
+ case "+": return a + b;
1082
+ case "-": return a - b;
1083
+ case "*": return a * b;
1084
+ case "/": return a / b;
1085
+ case "%": return a % b;
1086
+ case "^": return Math.pow(a, b);
1087
+ }
1088
+ };
1089
+
1090
+ // BOTH UNIT
1091
+ if (isUnit(left) && isUnit(right)) {
1092
+
1093
+ const from = this.findUnit(right.unit);
1094
+ const to = this.findUnit(left.unit);
1095
+
1096
+ if (from.type !== to.type) {
1097
+ throw new Error(`Cannot operate on different unit types`);
1098
+ }
1099
+
1100
+ // convert right → left unit
1101
+ const r = right.value * (from.data.value / to.data.value);
1102
+
1103
+ const result = apply(left.value, r);
1104
+
1105
+ // multiplication/division produce compound units
1106
+ if (op === "*") {
1107
+ return { value: result, unit: left.unit };
1108
+ }
1109
+
1110
+ if (op === "/") {
1111
+ return { value: result, unit: left.unit };
1112
+ }
1113
+
1114
+ if (op === "^") {
1115
+ return { value: result, unit: left.unit };
1116
+ }
1117
+
1118
+ return { value: result, unit: left.unit };
1119
+ }
1120
+
1121
+ // ================= LEFT UNIT =================
1122
+ if (isUnit(left) && !isUnit(right)) {
1123
+ const result = apply(left.value, right);
1124
+
1125
+ return { value: result, unit: left.unit };
1126
+ }
1127
+
1128
+ // ================= RIGHT UNIT =================
1129
+ if (!isUnit(left) && isUnit(right)) {
1130
+ const result = apply(left, right.value);
1131
+
1132
+ if (op === "/") {
1133
+ return { value: result, unit: right.unit };
1134
+ }
1135
+
1136
+ return { value: result, unit: right.unit };
1137
+ }
1138
+
1139
+ // ================= NORMAL =================
1140
+ return apply(left, right);
1141
+ },
1142
+ // Convert
1143
+ convert,
1144
+
1145
+ // Search helpers
1146
+ getAllUnitsFlat,
1147
+ findUnit
1148
+ };
1149
+ }
1150
+
1151
+ const globalUnits = {
1152
+ // Length
1153
+ length: {
1154
+ m: { value: 1, unit: 'meter', symbol: 'm' },
1155
+ cm: { value: 0.01, unit: 'centimeter', symbol: 'cm' },
1156
+ mm: { value: 0.001, unit: 'millimeter', symbol: 'mm' },
1157
+ km: { value: 1000, unit: 'kilometer', symbol: 'km' },
1158
+ um: { value: 0.000001, unit: 'micrometer', symbol: 'um', note: 'also called micron' },
1159
+ nm: { value: 0.000000001, unit: 'nanometer', symbol: 'nm' },
1160
+ px: { value: 0.000264583, unit: 'pixel', symbol: 'px', note: '96dpi standard' },
1161
+ em: { value: 0.000264583 * 16, unit: 'em', symbol: 'em', note: '1em = 16px by default' },
1162
+ rem: { value: 0.000264583 * 16, unit: 'rem', symbol: 'rem', note: 'root em = 16px by default' },
1163
+ pt: { value: 0.000352778, unit: 'point', symbol: 'pt', note: '1pt = 1/72 inch' },
1164
+ pc: { value: 0.00423333, unit: 'pica', symbol: 'pc', note: '1pc = 12pt' },
1165
+ inch: { value: 0.0254, unit: 'inch', symbol: 'in' },
1166
+ ft: { value: 0.3048, unit: 'foot', symbol: 'ft' },
1167
+ yd: { value: 0.9144, unit: 'yard', symbol: 'yd' },
1168
+ mi: { value: 1609.344, unit: 'mile', symbol: 'mi' },
1169
+ thou: { value: 0.0000254, unit: 'mil', symbol: 'thou', note: 'thousandth of an inch' },
1170
+ furlong: { value: 201.168, unit: 'furlong', symbol: 'fur', note: '220 yards' },
1171
+ nmi: { value: 1852, unit: 'nautical mile', symbol: 'nmi' },
1172
+ fathom: { value: 1.8288, unit: 'fathom', symbol: 'fathom' },
1173
+ au: { value: 1.496e11, unit: 'astronomical unit', symbol: 'AU' },
1174
+ ly: { value: 9.4607e15, unit: 'light year', symbol: 'ly' },
1175
+ pc: { value: 3.0857e16, unit: 'parsec', symbol: 'pc' }
1176
+ },
1177
+
1178
+ // Weight / Mass
1179
+ weight: {
1180
+ mg: { value: 1e-6, unit: 'milligram', symbol: 'mg' },
1181
+ g: { value: 0.001, unit: 'gram', symbol: 'g' },
1182
+ kg: { value: 1, unit: 'kilogram', symbol: 'kg' },
1183
+ t: { value: 1000, unit: 'tonne', symbol: 't', note: 'metric ton' },
1184
+ lb: { value: 0.453592, unit: 'pound', symbol: 'lb' },
1185
+ oz: { value: 0.0283495, unit: 'ounce', symbol: 'oz' },
1186
+ stone: { value: 6.35029, unit: 'stone', symbol: 'st', note: '1 stone = 14 lb' }
1187
+ },
1188
+
1189
+ // Time
1190
+ time: {
1191
+ s: { value: 1, unit: 'second', symbol: 's' },
1192
+ min: { value: 60, unit: 'minute', symbol: 'min' },
1193
+ h: { value: 3600, unit: 'hour', symbol: 'h' },
1194
+ day: { value: 86400, unit: 'day', symbol: 'd' },
1195
+ week: { value: 604800, unit: 'week', symbol: 'wk' },
1196
+ month: { value: 2629800, unit: 'month', symbol: 'mo', note: 'average month = 30.44 days' },
1197
+ year: { value: 31557600, unit: 'year', symbol: 'yr', note: 'average year = 365.25 days' }
1198
+ },
1199
+
1200
+ // Voltage
1201
+ voltage: {
1202
+ V: { value: 1, unit: 'volt', symbol: 'V' },
1203
+ mV: { value: 0.001, unit: 'millivolt', symbol: 'mV' },
1204
+ kV: { value: 1000, unit: 'kilovolt', symbol: 'kV' },
1205
+ MV: { value: 1e6, unit: 'megavolt', symbol: 'MV' },
1206
+ GV: { value: 1e9, unit: 'gigavolt', symbol: 'GV' },
1207
+ statV: { value: 299.792458, unit: 'statvolt', symbol: 'statV', note: 'CGS unit' },
1208
+ abV: { value: 1e-8, unit: 'abvolt', symbol: 'abV', note: 'CGS electromagnetic unit' }
1209
+ },
1210
+
1211
+ // Frequency
1212
+ frequency: {
1213
+ Hz: { value: 1, unit: 'hertz', symbol: 'Hz', note: '1 cycle per second' },
1214
+ kHz: { value: 1e3, unit: 'kilohertz', symbol: 'kHz' },
1215
+ MHz: { value: 1e6, unit: 'megahertz', symbol: 'MHz' },
1216
+ GHz: { value: 1e9, unit: 'gigahertz', symbol: 'GHz' },
1217
+ THz: { value: 1e12, unit: 'terahertz', symbol: 'THz' }
1218
+ },
1219
+
1220
+ // Power
1221
+ power: {
1222
+ W: { value: 1, unit: 'watt', symbol: 'W', note: '1 joule per second' },
1223
+ mW: { value: 0.001, unit: 'milliwatt', symbol: 'mW' },
1224
+ kW: { value: 1000, unit: 'kilowatt', symbol: 'kW' },
1225
+ MW: { value: 1e6, unit: 'megawatt', symbol: 'MW' },
1226
+ GW: { value: 1e9, unit: 'gigawatt', symbol: 'GW' },
1227
+ HP: { value: 745.7, unit: 'horsepower', symbol: 'HP', note: 'mechanical HP = 745.7 W' },
1228
+ kcal_per_h: { value: 1.163, unit: 'kilocalorie per hour', symbol: 'kcal/h', note: '= 1.163 W' },
1229
+ BTU_per_h: { value: 0.29307107, unit: 'BTU per hour', symbol: 'BTU/h', note: '= 0.293 W' }
1230
+ },
1231
+
1232
+ // Sound
1233
+ sound: {
1234
+ dB: { value: 1, unit: 'decibel', symbol: 'dB', note: 'logarithmic unit of sound intensity' },
1235
+ dBA: { value: 1, unit: 'A-weighted decibel', symbol: 'dBA', note: 'Adjusted for human hearing' },
1236
+ dBC: { value: 1, unit: 'C-weighted decibel', symbol: 'dBC', note: 'Flat weighting for high-level sounds' }
1237
+ },
1238
+
1239
+ // Temperature
1240
+ temperature: {
1241
+ K: { value: 1, unit: 'kelvin', symbol: 'K' },
1242
+ C: { value: 1, unit: 'Celsius', symbol: '°C', note: '°C → K: add 273.15' },
1243
+ F: { value: 1, unit: 'Fahrenheit', symbol: '°F', note: '°F → K: (°F - 32) * 5/9 + 273.15' }
1244
+ },
1245
+
1246
+ // Pressure
1247
+ pressure: {
1248
+ Pa: { value: 1, unit: 'pascal', symbol: 'Pa' },
1249
+ kPa: { value: 1000, unit: 'kilopascal', symbol: 'kPa' },
1250
+ MPa: { value: 1e6, unit: 'megapascal', symbol: 'MPa' },
1251
+ bar: { value: 1e5, unit: 'bar', symbol: 'bar' },
1252
+ atm: { value: 101325, unit: 'atmosphere', symbol: 'atm' },
1253
+ psi: { value: 6894.757, unit: 'pound per square inch', symbol: 'psi' },
1254
+ mmHg:{ value: 133.322, unit: 'millimeter of mercury', symbol: 'mmHg' }
1255
+ },
1256
+
1257
+ // Energy
1258
+ energy: {
1259
+ J: { value: 1, unit: 'joule', symbol: 'J' },
1260
+ kJ: { value: 1000, unit: 'kilojoule', symbol: 'kJ' },
1261
+ cal: { value: 4.184, unit: 'calorie', symbol: 'cal' },
1262
+ kcal:{ value: 4184, unit: 'kilocalorie', symbol: 'kcal' },
1263
+ eV: { value: 1.60218e-19, unit: 'electronvolt', symbol: 'eV' },
1264
+ BTU: { value: 1055.06, unit: 'BTU', symbol: 'BTU' }
1265
+ },
1266
+
1267
+ // Force
1268
+ force: {
1269
+ N: { value: 1, unit: 'newton', symbol: 'N' },
1270
+ kN: { value: 1000, unit: 'kilonewton', symbol: 'kN' },
1271
+ lbf: { value: 4.44822, unit: 'pound-force', symbol: 'lbf' },
1272
+ kgf: { value: 9.80665, unit: 'kilogram-force', symbol: 'kgf' },
1273
+ dyne:{ value: 1e-5, unit: 'dyne', symbol: 'dyn' }
1274
+ },
1275
+
1276
+ // Area
1277
+ area: {
1278
+ m2: { value: 1, unit: 'square meter', symbol: 'm²' },
1279
+ cm2: { value: 0.0001, unit: 'square centimeter', symbol: 'cm²' },
1280
+ km2: { value: 1e6, unit: 'square kilometer', symbol: 'km²' },
1281
+ acre: { value: 4046.856, unit: 'acre', symbol: 'acre' },
1282
+ hectare:{ value: 10000, unit: 'hectare', symbol: 'ha' },
1283
+ ft2: { value: 0.092903, unit: 'square foot', symbol: 'ft²' },
1284
+ yd2: { value: 0.836127, unit: 'square yard', symbol: 'yd²' }
1285
+ },
1286
+
1287
+ // Volume
1288
+ volume: {
1289
+ m3: { value: 1, unit: 'cubic meter', symbol: 'm³' },
1290
+ L: { value: 0.001, unit: 'liter', symbol: 'L' },
1291
+ mL: { value: 1e-6, unit: 'milliliter', symbol: 'mL' },
1292
+ gallon:{ value: 0.00378541, unit: 'US gallon', symbol: 'gal' },
1293
+ pint: { value: 0.000473176, unit: 'US pint', symbol: 'pt' },
1294
+ floz: { value: 2.9574e-5, unit: 'US fluid ounce', symbol: 'fl oz' }
1295
+ },
1296
+
1297
+ // Electrical Current
1298
+ current: {
1299
+ A: { value: 1, unit: 'ampere', symbol: 'A' },
1300
+ mA: { value: 0.001, unit: 'milliampere', symbol: 'mA' },
1301
+ uA: { value: 0.000001, unit: 'microampere', symbol: 'uA' },
1302
+ kA: { value: 1000, unit: 'kiloampere', symbol: 'kA' }
1303
+ },
1304
+
1305
+ // Resistance / Conductance
1306
+ resistance: {
1307
+ ohm: { value: 1, unit: 'ohm' },
1308
+ kohm: { value: 1000, unit: 'kiloohm'},
1309
+ megaohm: { value: 1e6, unit: 'megaohm'},
1310
+ S: { value: 1, unit: 'siemens', symbol: 'S', note: 'conductance' }
1311
+ },
1312
+
1313
+ // Capacitance / Inductance
1314
+ capacitance: {
1315
+ F: { value: 1, unit: 'farad', symbol: 'F' },
1316
+ mF: { value: 0.001, unit: 'millifarad'},
1317
+ uF: { value: 0.000001, unit: 'microfarad' }
1318
+ },
1319
+ inductance: {
1320
+ H: { value: 1, unit: 'henry', symbol: 'H' },
1321
+ mH: { value: 0.001, unit: 'millihenry', symbol: 'mH' },
1322
+ uH: { value: 0.000001, unit: 'microhenry', symbol: 'uH' }
1323
+ },
1324
+
1325
+ // Luminous Intensity / Illuminance
1326
+ light: {
1327
+ cd: { value: 1, unit: 'candela', symbol: 'cd' },
1328
+ lm: { value: 1, unit: 'lumen', symbol: 'lm' },
1329
+ lx: { value: 1, unit: 'lux', symbol: 'lx' }
1330
+ },
1331
+
1332
+ // Data / Digital Storage
1333
+ data: {
1334
+ bit: { value: 1, unit: 'bit', symbol: 'bit' },
1335
+ B: { value: 8, unit: 'byte', symbol: 'B' },
1336
+ KB: { value: 8e3, unit: 'kilobyte', symbol: 'KB' },
1337
+ MB: { value: 8e6, unit: 'megabyte', symbol: 'MB' },
1338
+ GB: { value: 8e9, unit: 'gigabyte', symbol: 'GB' },
1339
+ TB: { value: 8e12, unit: 'terabyte', symbol: 'TB' }
1340
+ },
1341
+
1342
+ // Angle
1343
+ angle: {
1344
+ deg: { value: 1, unit: 'degree', symbol: '°' },
1345
+ rad: { value: 57.2958, unit: 'radian', symbol: 'rad', note: '1 rad = 57.2958°' },
1346
+ grad:{ value: 0.9, unit: 'grad', symbol: 'grad', note: '1 grad = 0.9°' }
1347
+ },
1348
+ radiation: {
1349
+ // Absorbed Dose
1350
+ Gy: { value: 1, unit: 'gray', symbol: 'Gy', note: 'Absorbed dose: 1 Gy = 1 J/kg' },
1351
+ mGy: { value: 0.001, unit: 'milligray', symbol: 'mGy' },
1352
+ rad: { value: 0.01, unit: 'rad', symbol: 'rad', note: '1 rad = 0.01 Gy' },
1353
+
1354
+ // Dose Equivalent
1355
+ Sv: { value: 1, unit: 'sievert', symbol: 'Sv', note: 'Biological effect dose equivalent' },
1356
+ mSv: { value: 0.001, unit: 'millisievert', symbol: 'mSv' },
1357
+ rem: { value: 0.01, unit: 'rem', symbol: 'rem', note: '1 rem = 0.01 Sv' },
1358
+
1359
+ // Radioactivity
1360
+ Bq: { value: 1, unit: 'becquerel', symbol: 'Bq', note: '1 decay per second' },
1361
+ kBq: { value: 1e3, unit: 'kilobecquerel', symbol: 'kBq' },
1362
+ MBq: { value: 1e6, unit: 'megabecquerel', symbol: 'MBq' },
1363
+ GBq: { value: 1e9, unit: 'gigabecquerel', symbol: 'GBq' },
1364
+ Ci: { value: 3.7e10, unit: 'curie', symbol: 'Ci', note: '1 Ci = 3.7 x 10¹⁰ decays per second' },
1365
+ mCi: { value: 3.7e7, unit: 'millicurie', symbol: 'mCi' }
1366
+ }
1367
+ };
1368
+
1369
+ const validVarName = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
1370
+
1371
+ function createVarStore(initial = {}) {
1372
+ let store = Object.create(null);
1373
+
1374
+
1375
+ for (const key in initial) {
1376
+ store[key] = initial[key];
1377
+ }
1378
+
1379
+ return {
1380
+ set(name, value, { override = true } = {}) {
1381
+
1382
+ // Name validation
1383
+ if (typeof name !== "string" || !name) {
1384
+ throw new Error("Variable name must be a non-empty string");
1385
+ }
1386
+
1387
+ if (!validVarName.test(name)) {
1388
+ throw new Error(`Variable Name Error: '${name}' is not a valid variable name`);
1389
+ }
1390
+
1391
+ // Value validation
1392
+ if (value === undefined) {
1393
+ throw new Error(`Variable Value Error: '${name}' cannot be undefined`);
1394
+ }
1395
+
1396
+ // Prevent overwrite (optional)
1397
+ if (!override && name in variablesDB) {
1398
+ throw new Error(`Variable '${name}' already exists`);
1399
+ }
1400
+
1401
+ store[name] = value;
1402
+ },
1403
+
1404
+ //get variable
1405
+ get(name) {
1406
+ return store[name];
1407
+ },
1408
+
1409
+ // check existence
1410
+ has(name) {
1411
+ return Object.prototype.hasOwnProperty.call(store, name);
1412
+ },
1413
+
1414
+ // remove variable
1415
+ remove(name) {
1416
+ delete store[name];
1417
+ },
1418
+
1419
+ // get all variables (snapshot)
1420
+ all() {
1421
+ return { ...store };
1422
+ },
1423
+
1424
+ // clear all
1425
+ clear() {
1426
+ store = Object.create(null);
1427
+ },
1428
+
1429
+ // merge multiple variables
1430
+ merge(obj = {}) {
1431
+ for (const key in obj) {
1432
+ store[key] = obj[key];
1433
+ }
1434
+ },
1435
+
1436
+ // clone store (for scoped instances)
1437
+ clone() {
1438
+ return createVarStore(store);
1439
+ }
1440
+ };
452
1441
  }
453
1442
 
454
- class ViewPoint {
455
-
456
- constructor() {
457
- // Shared state
458
- this.variablesDB = variablesDB;
459
- this.func_DB_intrnl = internalFunctions;
460
- this.func_DB_extrnl = externalFunctions;
461
-
462
- this.operator_precedence = mathOperations.operator_precedence;
463
- }
464
-
465
- setVariable(name, value) {
466
- this.variablesDB[name] = value;
467
- }
468
-
469
- addFunction(name, fn) {
470
- this.func_DB_extrnl[name] = fn;
471
- }
472
-
473
- stringToJS(str) {
474
- return stringToJS.call(this, str, this.variablesDB);
475
- }
476
-
477
- evaluate(expr) {
478
-
479
- if (typeof expr !== "string") {
480
- throw new Error("Expression must be a string");
481
- }
482
-
483
- const context = {
484
- variablesDB: this.variablesDB,
485
- func_DB_intrnl: this.func_DB_intrnl,
486
- func_DB_extrnl: this.func_DB_extrnl,
487
- stringToJS: this.stringToJS.bind(this),
488
- evaluate: this.evaluate.bind(this)
489
- };
490
-
491
- // Step 1: Tokenize
492
- const tokens = tokenize(expr, context);
493
-
494
- // Step 2: Infix → Postfix
495
- const postfix = infixToPostfix(
496
- tokens,
497
- this.operator_precedence
498
- );
499
-
500
- // Step 3: Evaluate Postfix
501
- const result = evaluatePostfix(
502
- postfix,
503
- mathOperations
504
- );
505
-
506
- return result;
507
- }
1443
+ function createFunctionRegistry(initial = {}) {
1444
+ const store = Object.create(null);
1445
+
1446
+ for (const key in initial) {
1447
+ if (typeof initial[key] === "function") {
1448
+ store[key] = initial[key];
1449
+ }
1450
+ }
1451
+
1452
+ return {
1453
+ getAllFunctionsName() {
1454
+ return Object.keys(store);
1455
+ },
1456
+ // register new formula
1457
+ register(name, fn) {
1458
+ if (typeof name !== "string" || !name) {
1459
+ throw new Error("Formula name must be a non-empty string");
1460
+ }
1461
+
1462
+ if (typeof fn !== "function") {
1463
+ throw new Error(`Formula "${name}" must be callable`);
1464
+ }
1465
+
1466
+ store[name] = fn;
1467
+ },
1468
+
1469
+ // get formula
1470
+ get(name) {
1471
+ return store[name];
1472
+ },
1473
+
1474
+ // check existence
1475
+ has(name) {
1476
+ return Object.prototype.hasOwnProperty.call(store, name);
1477
+ },
1478
+
1479
+ // remove formula
1480
+ remove(name) {
1481
+ delete store[name];
1482
+ },
1483
+
1484
+ // list all
1485
+ all() {
1486
+ return { ...store };
1487
+ },
1488
+
1489
+ // clear registry
1490
+ clear() {
1491
+ for (const key in store) {
1492
+ delete store[key];
1493
+ }
1494
+ },
1495
+
1496
+ // extend multiple
1497
+ extend(formulas = {}) {
1498
+ for (const name in formulas) {
1499
+ if (typeof formulas[name] === "function") {
1500
+ store[name] = formulas[name];
1501
+ }
1502
+ }
1503
+ },
1504
+
1505
+ // clone (for scoped instances)
1506
+ clone() {
1507
+ return createFormulaRegistry(store);
1508
+ }
1509
+ };
1510
+ }
1511
+
1512
+ function validateSquareMatrix(matrix) {
1513
+ matrix = unwrapDenseMatrix(matrix);
1514
+ if (!Array.isArray(matrix) || matrix.length === 0) {
1515
+ throw new Error("det() expects a non-empty matrix");
1516
+ }
1517
+
1518
+ if (!matrix.every(Array.isArray)) {
1519
+ throw new Error("det() expects a 2D matrix");
1520
+ }
1521
+
1522
+ const size = matrix.length;
1523
+ if (!matrix.every((row) => row.length === size)) {
1524
+ throw new Error("det() expects a square matrix");
1525
+ }
1526
+
1527
+ for (const row of matrix) {
1528
+ for (const value of row) {
1529
+ if (typeof value !== "number" && typeof value !== "bigint") {
1530
+ throw new Error("det() matrix values must be numeric");
1531
+ }
1532
+ }
1533
+ }
1534
+ }
1535
+
1536
+ function determinant(matrix) {
1537
+ matrix = unwrapDenseMatrix(matrix);
1538
+ validateSquareMatrix(matrix);
1539
+
1540
+ if (matrix.length === 1) {
1541
+ return matrix[0][0];
1542
+ }
1543
+
1544
+ if (matrix.length === 2) {
1545
+ return (matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]);
1546
+ }
1547
+
1548
+ return matrix[0].reduce((sum, value, columnIndex) => {
1549
+ const minor = matrix.slice(1).map((row) =>
1550
+ row.filter((_, index) => index !== columnIndex)
1551
+ );
1552
+ const cofactor = columnIndex % 2 === 0 ? value : -value;
1553
+ return sum + (cofactor * determinant(minor));
1554
+ }, 0);
1555
+ }
1556
+
1557
+ function asMatrixData(value) {
1558
+ const data = unwrapDenseMatrix(value);
1559
+ if (!Array.isArray(data)) {
1560
+ throw new Error("Expected matrix data");
1561
+ }
1562
+ return data;
1563
+ }
1564
+
1565
+ function solveLinearSystem(coefficients, constants) {
1566
+ const n = coefficients.length;
1567
+ const augmented = coefficients.map((row, rowIndex) => [...row, constants[rowIndex]]);
1568
+
1569
+ for (let pivot = 0; pivot < n; pivot++) {
1570
+ let maxRow = pivot;
1571
+ let maxValue = Math.abs(augmented[pivot][pivot]);
1572
+
1573
+ for (let row = pivot + 1; row < n; row++) {
1574
+ const current = Math.abs(augmented[row][pivot]);
1575
+ if (current > maxValue) {
1576
+ maxValue = current;
1577
+ maxRow = row;
1578
+ }
1579
+ }
1580
+
1581
+ if (maxValue === 0) {
1582
+ throw new Error("Linear system is singular");
1583
+ }
1584
+
1585
+ if (maxRow !== pivot) {
1586
+ [augmented[pivot], augmented[maxRow]] = [augmented[maxRow], augmented[pivot]];
1587
+ }
1588
+
1589
+ const pivotValue = augmented[pivot][pivot];
1590
+ for (let col = pivot; col <= n; col++) {
1591
+ augmented[pivot][col] /= pivotValue;
1592
+ }
1593
+
1594
+ for (let row = 0; row < n; row++) {
1595
+ if (row === pivot) continue;
1596
+ const factor = augmented[row][pivot];
1597
+ for (let col = pivot; col <= n; col++) {
1598
+ augmented[row][col] -= factor * augmented[pivot][col];
1599
+ }
1600
+ }
1601
+ }
1602
+
1603
+ return augmented.map((row) => row[n]);
1604
+ }
1605
+
1606
+ function lupDecomposition(input) {
1607
+ const matrix = asMatrixData(input).map((row) => [...row]);
1608
+ validateSquareMatrix(matrix);
1609
+
1610
+ const n = matrix.length;
1611
+ const permutation = Array.from({ length: n }, (_, index) => index);
1612
+
1613
+ for (let pivot = 0; pivot < n; pivot++) {
1614
+ let maxRow = pivot;
1615
+ let maxValue = Math.abs(matrix[pivot][pivot]);
1616
+
1617
+ for (let row = pivot + 1; row < n; row++) {
1618
+ const current = Math.abs(matrix[row][pivot]);
1619
+ if (current > maxValue) {
1620
+ maxValue = current;
1621
+ maxRow = row;
1622
+ }
1623
+ }
1624
+
1625
+ if (maxValue === 0) {
1626
+ throw new Error("Matrix is singular");
1627
+ }
1628
+
1629
+ if (maxRow !== pivot) {
1630
+ [matrix[pivot], matrix[maxRow]] = [matrix[maxRow], matrix[pivot]];
1631
+ [permutation[pivot], permutation[maxRow]] = [permutation[maxRow], permutation[pivot]];
1632
+ }
1633
+
1634
+ for (let row = pivot + 1; row < n; row++) {
1635
+ matrix[row][pivot] /= matrix[pivot][pivot];
1636
+ for (let col = pivot + 1; col < n; col++) {
1637
+ matrix[row][col] -= matrix[row][pivot] * matrix[pivot][col];
1638
+ }
1639
+ }
1640
+ }
1641
+
1642
+ const L = matrix.map((row, rowIndex) =>
1643
+ row.map((value, colIndex) => {
1644
+ if (rowIndex === colIndex) return 1;
1645
+ if (rowIndex > colIndex) return value;
1646
+ return 0;
1647
+ })
1648
+ );
1649
+
1650
+ const U = matrix.map((row, rowIndex) =>
1651
+ row.map((value, colIndex) => (rowIndex <= colIndex ? value : 0))
1652
+ );
1653
+
1654
+ return {
1655
+ L: wrapDenseMatrix(L),
1656
+ U: wrapDenseMatrix(U),
1657
+ p: permutation
1658
+ };
1659
+ }
1660
+
1661
+ function linearSolve(aInput, bInput) {
1662
+ const { L, U, p } = lupDecomposition(aInput);
1663
+ const a = asMatrixData(aInput);
1664
+ const bData = asMatrixData(bInput);
1665
+ const bVector = Array.isArray(bData[0]) ? bData.map((row) => row[0]) : bData;
1666
+
1667
+ if (a.length !== bVector.length) {
1668
+ throw new Error("Right-hand side dimension mismatch");
1669
+ }
1670
+
1671
+ const permutedB = p.map((index) => bVector[index]);
1672
+ const y = new Array(a.length).fill(0);
1673
+
1674
+ for (let row = 0; row < a.length; row++) {
1675
+ y[row] = permutedB[row];
1676
+ for (let col = 0; col < row; col++) {
1677
+ y[row] -= L.data[row][col] * y[col];
1678
+ }
1679
+ }
1680
+
1681
+ const x = new Array(a.length).fill(0);
1682
+ for (let row = a.length - 1; row >= 0; row--) {
1683
+ x[row] = y[row];
1684
+ for (let col = row + 1; col < a.length; col++) {
1685
+ x[row] -= U.data[row][col] * x[col];
1686
+ }
1687
+ x[row] /= U.data[row][row];
1688
+ }
1689
+
1690
+ return wrapDenseMatrix(x.map((value) => [value]));
1691
+ }
1692
+
1693
+ function solveLyapunov(aInput, qInput) {
1694
+ const A = asMatrixData(aInput).map((row) => [...row]);
1695
+ const Q = asMatrixData(qInput).map((row) => [...row]);
1696
+ validateSquareMatrix(A);
1697
+ validateSquareMatrix(Q);
1698
+
1699
+ const n = A.length;
1700
+ if (Q.length !== n) {
1701
+ throw new Error("A and Q must have the same dimensions");
1702
+ }
1703
+
1704
+ const coefficients = [];
1705
+ const constants = [];
1706
+
1707
+ for (let row = 0; row < n; row++) {
1708
+ for (let col = 0; col < n; col++) {
1709
+ const equation = new Array(n * n).fill(0);
1710
+
1711
+ for (let k = 0; k < n; k++) {
1712
+ equation[k * n + col] += A[row][k];
1713
+ equation[row * n + k] += A[col][k];
1714
+ }
1715
+
1716
+ coefficients.push(equation);
1717
+ constants.push(-Q[row][col]);
1718
+ }
1719
+ }
1720
+
1721
+ const solution = solveLinearSystem(coefficients, constants);
1722
+ const X = [];
1723
+
1724
+ for (let row = 0; row < n; row++) {
1725
+ X.push(solution.slice(row * n, (row + 1) * n));
1726
+ }
1727
+
1728
+ return wrapDenseMatrix(X);
1729
+ }
1730
+
1731
+ function evaluatePolynomial(coefficients, x) {
1732
+ return coefficients.reduce((sum, coefficient, index) => sum + (coefficient * (x ** index)), 0);
1733
+ }
1734
+
1735
+ function syntheticDivide(coefficients, root) {
1736
+ const descending = [...coefficients].reverse();
1737
+ const quotient = [descending[0]];
1738
+
1739
+ for (let index = 1; index < descending.length - 1; index++) {
1740
+ quotient.push(descending[index] + (quotient[index - 1] * root));
1741
+ }
1742
+
1743
+ const remainder = descending[descending.length - 1] + (quotient[quotient.length - 1] * root);
1744
+ return {
1745
+ quotient: quotient.reverse(),
1746
+ remainder
1747
+ };
1748
+ }
1749
+
1750
+ function solveQuadratic(coefficients) {
1751
+ const [c, b, a] = coefficients;
1752
+ const discriminant = (b ** 2) - (4 * a * c);
1753
+ if (discriminant < 0) {
1754
+ throw new Error("Only real roots are supported");
1755
+ }
1756
+
1757
+ const sqrtDisc = Math.sqrt(discriminant);
1758
+ return [
1759
+ (-b + sqrtDisc) / (2 * a),
1760
+ (-b - sqrtDisc) / (2 * a)
1761
+ ];
1762
+ }
1763
+
1764
+ function polynomialRoots(...coefficients) {
1765
+ while (coefficients.length > 1 && coefficients[coefficients.length - 1] === 0) {
1766
+ coefficients.pop();
1767
+ }
1768
+
1769
+ const degree = coefficients.length - 1;
1770
+ if (degree < 1) {
1771
+ throw new Error("polynomialRoot() expects at least a linear polynomial");
1772
+ }
1773
+
1774
+ if (degree === 1) {
1775
+ const [b, a] = coefficients;
1776
+ return [-b / a];
1777
+ }
1778
+
1779
+ if (degree === 2) {
1780
+ return solveQuadratic(coefficients);
1781
+ }
1782
+
1783
+ if (degree === 3) {
1784
+ const constant = coefficients[0];
1785
+ coefficients[3];
1786
+ const candidates = [];
1787
+ const limit = Math.abs(constant);
1788
+
1789
+ for (let divisor = 1; divisor <= Math.max(1, limit); divisor++) {
1790
+ if (limit % divisor === 0) {
1791
+ candidates.push(divisor, -divisor);
1792
+ }
1793
+ }
1794
+
1795
+ for (const candidate of candidates) {
1796
+ if (evaluatePolynomial(coefficients, candidate) === 0) {
1797
+ const reduced = syntheticDivide(coefficients, candidate);
1798
+ const remainingRoots = solveQuadratic(reduced.quotient);
1799
+ return [candidate, ...remainingRoots];
1800
+ }
1801
+ }
1802
+ }
1803
+
1804
+ throw new Error("polynomialRoot() currently supports degree up to 3");
1805
+ }
1806
+
1807
+ function dotProduct(a, b) {
1808
+ return a.reduce((sum, value, index) => sum + (value * b[index]), 0);
1809
+ }
1810
+
1811
+ function vectorNorm(vector) {
1812
+ return Math.sqrt(dotProduct(vector, vector));
1813
+ }
1814
+
1815
+ function scaleVector(vector, scalar) {
1816
+ return vector.map((value) => value * scalar);
1817
+ }
1818
+
1819
+ function subtractVectors(a, b) {
1820
+ return a.map((value, index) => value - b[index]);
1821
+ }
1822
+
1823
+ function transpose(matrix) {
1824
+ return matrix[0].map((_, colIndex) => matrix.map((row) => row[colIndex]));
1825
+ }
1826
+
1827
+ function qrDecomposition(input) {
1828
+ const A = asMatrixData(input).map((row) => [...row]);
1829
+ if (!A.length || !A.every((row) => row.length === A[0].length)) {
1830
+ throw new Error("qr() expects a rectangular matrix");
1831
+ }
1832
+
1833
+ const rowCount = A.length;
1834
+ const colCount = A[0].length;
1835
+ const columns = transpose(A);
1836
+ const qColumns = [];
1837
+
1838
+ for (let col = 0; col < colCount; col++) {
1839
+ let vector = [...columns[col]];
1840
+
1841
+ for (let existing = 0; existing < qColumns.length; existing++) {
1842
+ const projection = dotProduct(qColumns[existing], columns[col]);
1843
+ vector = subtractVectors(vector, scaleVector(qColumns[existing], projection));
1844
+ }
1845
+
1846
+ const norm = vectorNorm(vector);
1847
+ if (norm === 0) {
1848
+ throw new Error("qr() requires linearly independent columns");
1849
+ }
1850
+
1851
+ qColumns.push(scaleVector(vector, 1 / norm));
1852
+ }
1853
+
1854
+ for (let basisIndex = 0; qColumns.length < rowCount && basisIndex < rowCount; basisIndex++) {
1855
+ let candidate = Array.from({ length: rowCount }, (_, index) => (index === basisIndex ? 1 : 0));
1856
+
1857
+ for (const column of qColumns) {
1858
+ const projection = dotProduct(column, candidate);
1859
+ candidate = subtractVectors(candidate, scaleVector(column, projection));
1860
+ }
1861
+
1862
+ const norm = vectorNorm(candidate);
1863
+ if (norm > 1e-10) {
1864
+ qColumns.push(scaleVector(candidate, 1 / norm));
1865
+ }
1866
+ }
1867
+
1868
+ const Q = Array.from({ length: rowCount }, (_, rowIndex) =>
1869
+ qColumns.map((column) => column[rowIndex])
1870
+ );
1871
+
1872
+ const fullR = Array.from({ length: rowCount }, () => Array(colCount).fill(0));
1873
+ for (let row = 0; row < rowCount; row++) {
1874
+ for (let col = 0; col < colCount; col++) {
1875
+ fullR[row][col] = dotProduct(qColumns[row], columns[col]);
1876
+ }
1877
+ }
1878
+
1879
+ return {
1880
+ Q: wrapDenseMatrix(Q),
1881
+ R: wrapDenseMatrix(fullR)
1882
+ };
1883
+ }
1884
+
1885
+ function splitTerms(expression) {
1886
+ const normalized = expression.replace(/\s+/g, "");
1887
+ if (!normalized) {
1888
+ return [];
1889
+ }
1890
+
1891
+ return normalized
1892
+ .replace(/-/g, "+-")
1893
+ .split("+")
1894
+ .filter(Boolean);
1895
+ }
1896
+
1897
+ function parsePolynomial(expression, variable) {
1898
+ const terms = splitTerms(expression);
1899
+ const coefficients = new Map();
1900
+
1901
+ for (const term of terms) {
1902
+ if (term.includes(variable)) {
1903
+ const [rawCoeff, rawPower] = term.split(variable);
1904
+ let coefficient;
1905
+
1906
+ if (rawCoeff === "" || rawCoeff === "+") coefficient = 1;
1907
+ else if (rawCoeff === "-") coefficient = -1;
1908
+ else {
1909
+ const cleaned = rawCoeff.endsWith("*") ? rawCoeff.slice(0, -1) : rawCoeff;
1910
+ coefficient = Number(cleaned);
1911
+ }
1912
+
1913
+ if (!Number.isFinite(coefficient)) {
1914
+ throw new Error("Unsupported algebra term");
1915
+ }
1916
+
1917
+ let power = 1;
1918
+ if (rawPower) {
1919
+ if (!rawPower.startsWith("^")) {
1920
+ throw new Error("Unsupported algebra term");
1921
+ }
1922
+
1923
+ power = Number(rawPower.slice(1));
1924
+ }
1925
+
1926
+ if (!Number.isInteger(power) || power < 0) {
1927
+ throw new Error("Only non-negative integer powers are supported");
1928
+ }
1929
+
1930
+ coefficients.set(power, (coefficients.get(power) || 0) + coefficient);
1931
+ } else {
1932
+ const constant = Number(term);
1933
+ if (!Number.isFinite(constant)) {
1934
+ throw new Error("Unsupported algebra term");
1935
+ }
1936
+ coefficients.set(0, (coefficients.get(0) || 0) + constant);
1937
+ }
1938
+ }
1939
+
1940
+ return coefficients;
1941
+ }
1942
+
1943
+ function formatPolynomial(coefficients, variable) {
1944
+ const ordered = [...coefficients.entries()]
1945
+ .filter(([, coefficient]) => coefficient !== 0)
1946
+ .sort((a, b) => b[0] - a[0]);
1947
+
1948
+ if (!ordered.length) {
1949
+ return "0";
1950
+ }
1951
+
1952
+ return ordered.map(([power, coefficient], index) => {
1953
+ const negative = coefficient < 0;
1954
+ const absCoeff = Math.abs(coefficient);
1955
+ let body;
1956
+
1957
+ if (power === 0) {
1958
+ body = `${absCoeff}`;
1959
+ } else if (power === 1) {
1960
+ body = absCoeff === 1 ? variable : `${absCoeff} * ${variable}`;
1961
+ } else {
1962
+ body = absCoeff === 1
1963
+ ? `${variable}^${power}`
1964
+ : `${absCoeff} * ${variable}^${power}`;
1965
+ }
1966
+
1967
+ if (index === 0) {
1968
+ return negative ? `-${body}` : body;
1969
+ }
1970
+
1971
+ return negative ? `- ${body}` : `+ ${body}`;
1972
+ }).join(" ");
1973
+ }
1974
+
1975
+ function simplifyExpression(expression) {
1976
+ const compact = expression.replace(/\s+/g, "");
1977
+ const variableMatch = compact.match(/[a-zA-Z]+/);
1978
+ const variable = variableMatch?.[0] || "x";
1979
+ const coefficients = parsePolynomial(expression, variable);
1980
+ return formatPolynomial(coefficients, variable);
1981
+ }
1982
+
1983
+ function derivativeExpression(expression, variable) {
1984
+ const coefficients = parsePolynomial(expression, variable);
1985
+ const derived = new Map();
1986
+
1987
+ for (const [power, coefficient] of coefficients.entries()) {
1988
+ if (power === 0) continue;
1989
+ derived.set(power - 1, (derived.get(power - 1) || 0) + (coefficient * power));
1990
+ }
1991
+
1992
+ return formatPolynomial(derived, variable);
1993
+ }
1994
+
1995
+ const internalFunctions = {
1996
+ max: (...args) => {
1997
+ if (!args.length) throw new Error("max() requires arguments");
1998
+ return Math.max(...args);
1999
+ },
2000
+
2001
+ min: (...args) => {
2002
+ if (!args.length) throw new Error("min() requires arguments");
2003
+ return Math.min(...args);
2004
+ },
2005
+
2006
+ abs: (x) => Math.abs(x),
2007
+
2008
+ round: (x) => Math.round(x),
2009
+
2010
+ floor: (x) => Math.floor(x),
2011
+
2012
+ ceil: (x) => Math.ceil(x),
2013
+
2014
+ sqrt: (x) => {
2015
+ if (x < 0) throw new Error("sqrt() domain error");
2016
+ return Math.sqrt(x);
2017
+ },
2018
+
2019
+ pow: (a, b) => a ** b,
2020
+ det: (matrix) => determinant(matrix),
2021
+ polynomialRoot: (...coefficients) => polynomialRoots(...coefficients),
2022
+ lsolve: (a, b) => linearSolve(a, b),
2023
+ lup: (matrix) => lupDecomposition(matrix),
2024
+ lyap: (a, q) => solveLyapunov(a, q),
2025
+ qr: (matrix) => qrDecomposition(matrix),
2026
+ simplify: (expression) => {
2027
+ if (typeof expression !== "string") {
2028
+ throw new Error("simplify() expects an expression string");
2029
+ }
2030
+ return simplifyExpression(expression);
2031
+ },
2032
+ derivative: (expression, variable = "x") => {
2033
+ if (typeof expression !== "string" || typeof variable !== "string") {
2034
+ throw new Error("derivative() expects expression and variable strings");
2035
+ }
2036
+ return derivativeExpression(expression, variable);
2037
+ },
2038
+
2039
+ /* ================= TRIGONOMETRY ================= */
2040
+
2041
+ sin: (x) => Math.sin(x),
2042
+ cos: (x) => Math.cos(x),
2043
+ tan: (x) => Math.tan(x),
2044
+
2045
+ asin: (x) => Math.asin(x),
2046
+ acos: (x) => Math.acos(x),
2047
+ atan: (x) => Math.atan(x),
2048
+
2049
+ /* ================= LOG / EXP ================= */
2050
+
2051
+ log: (x) => {
2052
+ if (x <= 0) throw new Error("log() domain error");
2053
+ return Math.log(x);
2054
+ },
2055
+
2056
+ log10: (x) => {
2057
+ if (x <= 0) throw new Error("log10() domain error");
2058
+ return Math.log10(x);
2059
+ },
2060
+
2061
+ exp: (x) => Math.exp(x),
2062
+
2063
+ /* ================= RANDOM ================= */
2064
+
2065
+ random: () => Math.random(),
2066
+
2067
+ /* ================= BOOLEAN / LOGIC ================= */
2068
+
2069
+ and: (a, b) => Boolean(a && b),
2070
+
2071
+ or: (a, b) => Boolean(a || b),
2072
+
2073
+ not: (a) => !a,
2074
+ "!": (a) => !a,
2075
+
2076
+ /* ================= COMPARISON ================= */
2077
+
2078
+ eq: (a, b) => a === b,
2079
+
2080
+ neq: (a, b) => a !== b,
2081
+ "notEqual": (a, b) => a !== b,
2082
+
2083
+ gt: (a, b) => a > b,
2084
+ "greaterThan": (a, b) => a > b,
2085
+
2086
+ lt: (a, b) => a < b,
2087
+ "lessThan": (a, b) => a < b,
2088
+
2089
+ gte: (a, b) => a >= b,
2090
+ "greaterThanOrEqual": (a, b) => a >= b,
2091
+
2092
+ lte: (a, b) => a <= b,
2093
+ "lessThanOrEqual": (a, b) => a <= b,
2094
+
2095
+ /* ================= UTILITY ================= */
2096
+
2097
+ clamp: (x, min, max) => {
2098
+ if (min > max) throw new Error("clamp(): min > max");
2099
+ return Math.min(Math.max(x, min), max);
2100
+ },
2101
+
2102
+ if: (condition, a, b) => (condition ? a : b),
2103
+
2104
+ /* ================= TYPE ================= */
2105
+
2106
+ typeof: (x) => typeof x,
2107
+
2108
+ /* ================= STRING ================= */
2109
+
2110
+ length: (x) => {
2111
+ if (typeof x === "string" || Array.isArray(x)) {
2112
+ return x.length;
2113
+ }
2114
+ throw new Error("length() expects string or array");
2115
+ }
2116
+ };
2117
+
2118
+ function buildAST(tokens) {
2119
+ let current = 0;
2120
+
2121
+ const peek = () => tokens[current];
2122
+ const consume = () => tokens[current++];
2123
+
2124
+ const match = (type, value) => {
2125
+ const t = peek();
2126
+ if (!t) return false;
2127
+
2128
+ if (t.type !== type) return false;
2129
+
2130
+ if (value !== undefined && t.value !== value) return false;
2131
+
2132
+ current++;
2133
+ return true;
2134
+ };
2135
+
2136
+ const parseSliceOrIndex = () => {
2137
+ let start = null;
2138
+
2139
+ if (!(peek()?.type === "Colon" || peek()?.type === "Comma" || peek()?.type === "ArrayEnd")) {
2140
+ start = parseExpression();
2141
+ }
2142
+
2143
+ if (match("Colon")) {
2144
+ let end = null;
2145
+
2146
+ if (!(peek()?.type === "Comma" || peek()?.type === "ArrayEnd")) {
2147
+ end = parseExpression();
2148
+ }
2149
+
2150
+ return {
2151
+ type: "SliceExpression",
2152
+ start,
2153
+ end
2154
+ };
2155
+ }
2156
+
2157
+ return start;
2158
+ };
2159
+
2160
+ /* ================= PRIMARY ================= */
2161
+ function parsePrimary() {
2162
+ const token = consume();
2163
+ if (!token) throw new Error("Unexpected end of input");
2164
+
2165
+ switch (token.type) {
2166
+ case "Number":
2167
+ case "BigInt":
2168
+ case "Boolean":
2169
+ case "String":
2170
+ return { type: "Literal", value: token.value };
2171
+
2172
+ case "ImaginaryLiteral":
2173
+ return { type: "ImaginaryLiteral", value: token.value };
2174
+
2175
+ case "NumberWithUnit":
2176
+ return {
2177
+ type: "UnitLiteral",
2178
+ value: token.value,
2179
+ unit: token.unit
2180
+ };
2181
+
2182
+ case "Identifier":
2183
+ return { type: "Identifier", name: token.name };
2184
+
2185
+ case "Function":
2186
+ return {
2187
+ type: "Identifier",
2188
+ name: token.name
2189
+ };
2190
+
2191
+ case "Parenthesis":
2192
+ if (token.value === "(") {
2193
+ const expr = parseExpression();
2194
+
2195
+ if (!match("Parenthesis", ")")) {
2196
+ throw new Error(`Expected ')'`);
2197
+ }
2198
+
2199
+ return expr;
2200
+ }
2201
+
2202
+ case "ArrayStart": {
2203
+ const rows = [];
2204
+ let currentRow = [];
2205
+
2206
+ if (!match("ArrayEnd")) {
2207
+ while (true) {
2208
+ currentRow.push(parseExpression());
2209
+
2210
+ if (match("Comma")) {
2211
+ continue;
2212
+ }
2213
+
2214
+ if (match("Semicolon")) {
2215
+ rows.push(currentRow);
2216
+ currentRow = [];
2217
+ continue;
2218
+ }
2219
+
2220
+ if (match("ArrayEnd")) {
2221
+ rows.push(currentRow);
2222
+ break;
2223
+ }
2224
+
2225
+ throw new Error(`Expected ',', ';', or ']' at ${current}`);
2226
+ }
2227
+ }
2228
+
2229
+ if (!rows.length) {
2230
+ return { type: "ArrayExpression", elements: [] };
2231
+ }
2232
+
2233
+ if (rows.length === 1) {
2234
+ return { type: "ArrayExpression", elements: rows[0] };
2235
+ }
2236
+
2237
+ return {
2238
+ type: "ArrayExpression",
2239
+ elements: rows.map((elements) => ({
2240
+ type: "ArrayExpression",
2241
+ elements
2242
+ }))
2243
+ };
2244
+ }
2245
+
2246
+ case "BlockStart": {
2247
+ const properties = [];
2248
+
2249
+ if (!match("BlockEnd")) {
2250
+ do {
2251
+ const keyToken = consume();
2252
+
2253
+ if (
2254
+ keyToken.type !== "Identifier" &&
2255
+ keyToken.type !== "String"
2256
+ ) {
2257
+ throw new Error("Invalid object key");
2258
+ }
2259
+
2260
+ if (!match("Colon")) {
2261
+ throw new Error("Expected ':' after key");
2262
+ }
2263
+
2264
+ const value = parseExpression();
2265
+
2266
+ properties.push({
2267
+ key: keyToken.value,
2268
+ value
2269
+ });
2270
+
2271
+ } while (match("Comma"));
2272
+
2273
+ if (!match("BlockEnd")) {
2274
+ throw new Error(`Expected '}' at ${current}`);
2275
+ }
2276
+ }
2277
+
2278
+ return { type: "ObjectExpression", properties };
2279
+ }
2280
+ }
2281
+
2282
+ throw new Error(`Unexpected token: ${JSON.stringify(token)}`);
2283
+ }
2284
+
2285
+ /* ================= MEMBER ================= */
2286
+ function parseMember() {
2287
+ let object = parsePrimary();
2288
+
2289
+ while (true) {
2290
+ if (match("ArrayStart")) {
2291
+ const selectors = [];
2292
+
2293
+ if (!match("ArrayEnd")) {
2294
+ do {
2295
+ selectors.push(parseSliceOrIndex());
2296
+ } while (match("Comma"));
2297
+
2298
+ if (!match("ArrayEnd")) {
2299
+ throw new Error(`Expected ']' at ${current}`);
2300
+ }
2301
+ }
2302
+
2303
+ object = {
2304
+ type: "IndexExpression",
2305
+ object,
2306
+ selectors
2307
+ };
2308
+ continue;
2309
+ }
2310
+
2311
+ if (match("Dot")) {
2312
+ const property = consume();
2313
+
2314
+ if (property.type !== "Identifier") {
2315
+ throw new Error("Expected property after '.'");
2316
+ }
2317
+
2318
+ object = {
2319
+ type: "MemberExpression",
2320
+ object,
2321
+ property: { type: "Identifier", name: property.value },
2322
+ optional: false
2323
+ };
2324
+ continue;
2325
+ }
2326
+
2327
+ if (match("Operator", "?.")) {
2328
+ const property = consume();
2329
+
2330
+ object = {
2331
+ type: "MemberExpression",
2332
+ object,
2333
+ property: { type: "Identifier", name: property.value },
2334
+ optional: true
2335
+ };
2336
+ continue;
2337
+ }
2338
+
2339
+ break;
2340
+ }
2341
+
2342
+ return object;
2343
+ }
2344
+
2345
+ /* ================= CALL ================= */
2346
+ function parseCallChain() {
2347
+ let expr = parseMember();
2348
+
2349
+ while (peek()?.type === "Parenthesis" && peek()?.value === "(") {
2350
+ consume(); // '('
2351
+
2352
+ const args = [];
2353
+
2354
+ if (!(peek()?.type === "Parenthesis" && peek()?.value === ")")) {
2355
+ do {
2356
+ args.push(parseExpression());
2357
+ } while (match("Comma"));
2358
+ }
2359
+
2360
+ if (!match("Parenthesis", ")")) {
2361
+ throw new Error(`Expected ')' at ${current}`);
2362
+ }
2363
+
2364
+ expr = {
2365
+ type: "CallExpression",
2366
+ callee: expr,
2367
+ arguments: args
2368
+ };
2369
+ }
2370
+
2371
+ return expr;
2372
+ }
2373
+
2374
+ /* ================= UNARY ================= */
2375
+ function parseUnary() {
2376
+ if (match("UnaryOperator")) {
2377
+ const operator = tokens[current - 1].value;
2378
+
2379
+ return {
2380
+ type: "UnaryExpression",
2381
+ operator,
2382
+ argument: parseUnary()
2383
+ };
2384
+ }
2385
+
2386
+ return parseCallChain();
2387
+ }
2388
+
2389
+ /* ================= POWER ================= */
2390
+ function parsePower() {
2391
+ let left = parseUnary();
2392
+
2393
+ if (match("Operator", "^")) {
2394
+ const right = parsePower();
2395
+ return {
2396
+ type: "BinaryExpression",
2397
+ operator: "^",
2398
+ left,
2399
+ right
2400
+ };
2401
+ }
2402
+
2403
+ return left;
2404
+ }
2405
+
2406
+ /* ================= MULT ================= */
2407
+ function parseMultiplication() {
2408
+ let left = parsePower();
2409
+
2410
+ while (
2411
+ match("Operator", "*") ||
2412
+ match("Operator", "/") ||
2413
+ match("Operator", "%")
2414
+ ) {
2415
+ const operator = tokens[current - 1].value;
2416
+ const right = parsePower();
2417
+
2418
+ left = {
2419
+ type: "BinaryExpression",
2420
+ operator,
2421
+ left,
2422
+ right
2423
+ };
2424
+ }
2425
+
2426
+ return left;
2427
+ }
2428
+
2429
+ /* ================= ADD ================= */
2430
+ function parseAddition() {
2431
+ let left = parseMultiplication();
2432
+
2433
+ while (match("Operator", "+") || match("Operator", "-")) {
2434
+ const operator = tokens[current - 1].value;
2435
+ const right = parseMultiplication();
2436
+
2437
+ left = {
2438
+ type: "BinaryExpression",
2439
+ operator,
2440
+ left,
2441
+ right
2442
+ };
2443
+ }
2444
+
2445
+ return left;
2446
+ }
2447
+
2448
+ /* ================= UNIT CONVERSION ================= */
2449
+ function parseUnitConversion() {
2450
+ let left = parseAddition();
2451
+
2452
+ const nextKeyword = peek();
2453
+ if (nextKeyword?.type === "Keyword" && ["to", "in"].includes(nextKeyword.value)) {
2454
+ consume();
2455
+ const next = consume();
2456
+
2457
+ if (!next || next.type !== "Unit") {
2458
+ throw new Error(`Expected unit after '${nextKeyword.value}'`);
2459
+ }
2460
+
2461
+ return {
2462
+ type: "UnitConversion",
2463
+ from: left,
2464
+ to: next.value
2465
+ };
2466
+ }
2467
+
2468
+ return left;
2469
+ }
2470
+
2471
+ /* ================= COMPARISON ================= */
2472
+ function parseComparison() {
2473
+ let left = parseUnitConversion();
2474
+
2475
+ while (
2476
+ match("Operator", ">") ||
2477
+ match("Operator", "<") ||
2478
+ match("Operator", ">=") ||
2479
+ match("Operator", "<=") ||
2480
+ match("Operator", "==")
2481
+ ) {
2482
+ const operator = tokens[current - 1].value;
2483
+ const right = parseUnitConversion();
2484
+
2485
+ left = {
2486
+ type: "BinaryExpression",
2487
+ operator,
2488
+ left,
2489
+ right
2490
+ };
2491
+ }
2492
+
2493
+ return left;
2494
+ }
2495
+
2496
+ /* ================= LOGICAL ================= */
2497
+ function parseLogical() {
2498
+ let left = parseComparison();
2499
+
2500
+ while (
2501
+ match("Operator", "&&") ||
2502
+ match("Operator", "||")
2503
+ ) {
2504
+ const operator = tokens[current - 1].value;
2505
+ const right = parseComparison();
2506
+
2507
+ left = {
2508
+ type: "LogicalExpression",
2509
+ operator,
2510
+ left,
2511
+ right
2512
+ };
2513
+ }
2514
+
2515
+ return left;
2516
+ }
2517
+
2518
+ /* ================= NULLISH ================= */
2519
+ function parseNullish() {
2520
+ let left = parseLogical();
2521
+
2522
+ while (match("Operator", "??")) {
2523
+ const right = parseLogical();
2524
+
2525
+ left = {
2526
+ type: "LogicalExpression",
2527
+ operator: "??",
2528
+ left,
2529
+ right
2530
+ };
2531
+ }
2532
+
2533
+ return left;
2534
+ }
2535
+
2536
+ /* ================= TERNARY ================= */
2537
+ function parseTernary() {
2538
+ let test = parseNullish();
2539
+
2540
+ if (match("Ternary", "?")) {
2541
+ const consequent = parseExpression();
2542
+
2543
+ if (!match("Ternary", ":")) {
2544
+ throw new Error("Expected ':' in ternary");
2545
+ }
2546
+
2547
+ const alternate = parseExpression();
2548
+
2549
+ return {
2550
+ type: "ConditionalExpression",
2551
+ test,
2552
+ consequent,
2553
+ alternate
2554
+ };
2555
+ }
2556
+
2557
+ return test;
2558
+ }
2559
+
2560
+ /* ================= PIPELINE ================= */
2561
+ function parsePipeline() {
2562
+ let left = parseTernary();
2563
+
2564
+ while (match("Operator", "|>")) {
2565
+ const right = parseTernary();
2566
+
2567
+ left = {
2568
+ type: "PipelineExpression",
2569
+ left,
2570
+ right
2571
+ };
2572
+ }
2573
+
2574
+ return left;
2575
+ }
2576
+
2577
+ /* ================= ASSIGNMENT ================= */
2578
+ function parseAssignment() {
2579
+ let left = parsePipeline();
2580
+
2581
+ if (
2582
+ match("Operator", "=") ||
2583
+ match("Operator", "+=") ||
2584
+ match("Operator", "-=") ||
2585
+ match("Operator", "*=") ||
2586
+ match("Operator", "/=")
2587
+ ) {
2588
+ const operator = tokens[current - 1].value;
2589
+
2590
+ if (left.type === "CallExpression") {
2591
+ const isFunctionTarget =
2592
+ left.callee?.type === "Identifier" &&
2593
+ left.arguments.every((arg) => arg.type === "Identifier");
2594
+
2595
+ if (!isFunctionTarget) {
2596
+ throw new Error("Invalid function definition");
2597
+ }
2598
+
2599
+ const right = parseAssignment();
2600
+
2601
+ return {
2602
+ type: "FunctionAssignmentExpression",
2603
+ operator,
2604
+ left: {
2605
+ type: "Identifier",
2606
+ name: left.callee.name
2607
+ },
2608
+ params: left.arguments.map((arg) => arg.name),
2609
+ right
2610
+ };
2611
+ }
2612
+
2613
+ if (
2614
+ left.type !== "Identifier" &&
2615
+ left.type !== "MemberExpression" &&
2616
+ left.type !== "IndexExpression"
2617
+ ) {
2618
+ throw new Error("Invalid assignment target");
2619
+ }
2620
+
2621
+ const right = parseAssignment();
2622
+
2623
+ return {
2624
+ type: "AssignmentExpression",
2625
+ operator,
2626
+ left,
2627
+ right
2628
+ };
2629
+ }
2630
+
2631
+ return left;
2632
+ }
2633
+
2634
+ /* ================= ENTRY ================= */
2635
+ function parseExpression() {
2636
+ return parseAssignment();
2637
+ }
2638
+
2639
+ const ast = parseExpression();
2640
+
2641
+ if (current < tokens.length) {
2642
+ throw new Error(
2643
+ `Unexpected token at end: ${JSON.stringify(peek())}`
2644
+ );
2645
+ }
2646
+
2647
+ return ast;
2648
+ }
2649
+
2650
+ //
2651
+
2652
+ const isComplex = (value) =>
2653
+ value && typeof value === "object" && "re" in value && "im" in value;
2654
+
2655
+ const isUnitValue = (value) =>
2656
+ value && typeof value === "object" && "value" in value && "unit" in value;
2657
+
2658
+ const isMatrix = (value) =>
2659
+ Array.isArray(value) && value.length > 0 && value.every(Array.isArray);
2660
+
2661
+ const formatComplex = (value) => {
2662
+ if (!isComplex(value)) return value;
2663
+
2664
+ const real = value.re;
2665
+ const imaginary = Math.abs(value.im);
2666
+ const sign = value.im < 0 ? "-" : "+";
2667
+
2668
+ if (real === 0) {
2669
+ if (value.im === 1) return "i";
2670
+ if (value.im === -1) return "-i";
2671
+ return `${value.im}i`;
2672
+ }
2673
+
2674
+ const imagPart = imaginary === 1 ? "i" : `${imaginary}i`;
2675
+ return `${real} ${sign} ${imagPart}`;
2676
+ };
2677
+
2678
+ const formatScalar = (value) => {
2679
+ if (typeof value !== "number") {
2680
+ return String(value);
2681
+ }
2682
+
2683
+ if (Number.isInteger(value)) {
2684
+ return String(value);
2685
+ }
2686
+
2687
+ return Number(value.toFixed(14)).toString();
2688
+ };
2689
+
2690
+ const formatResult = (value) => {
2691
+ if (isComplex(value)) {
2692
+ return formatComplex(value);
2693
+ }
2694
+
2695
+ if (isUnitValue(value)) {
2696
+ return `${value.value} ${value.unit}`;
2697
+ }
2698
+
2699
+ if (isDenseMatrixWrapper(value)) {
2700
+ return serializeExprifyValue(value);
2701
+ }
2702
+
2703
+ if (isMatrix(value)) {
2704
+ return value.map((row) => row.map(formatScalar).join("\t")).join("\n");
2705
+ }
2706
+
2707
+ if (Array.isArray(value)) {
2708
+ return JSON.stringify(value);
2709
+ }
2710
+
2711
+ if (value && typeof value === "object") {
2712
+ return serializeExprifyValue(value);
2713
+ }
2714
+
2715
+ return value;
2716
+ };
2717
+
2718
+ class exprify {
2719
+ constructor() {
2720
+ // Shared state
2721
+ this.math = mathOperations;
2722
+ this.units = createUnitsStore(globalUnits);
2723
+ this.functions = createFunctionRegistry(internalFunctions);
2724
+ this.variables = createVarStore();
2725
+ this._cache = new Map();
2726
+ this.variables.set("pi", Math.PI);
2727
+ this.variables.set("e", Math.E);
2728
+ this.addFunction("parse", (expression) => {
2729
+ if (typeof expression !== "string") {
2730
+ throw new Error("parse() expects an expression string");
2731
+ }
2732
+ return expression;
2733
+ });
2734
+ this.addFunction("leafCount", (value) => {
2735
+ const countLeafTokens = (expression) => {
2736
+ const strippedKeys = expression.replace(/(^|[{,]\s*)[a-zA-Z_][a-zA-Z0-9_]*\s*:/g, "$1");
2737
+ const matches = strippedKeys.match(/\d+(\.\d+)?(e[+-]?\d+)?n?|[a-zA-Z_][a-zA-Z0-9_]*/gi);
2738
+ return matches ? matches.length : 0;
2739
+ };
2740
+
2741
+ let ast = value;
2742
+ if (typeof value === "string") {
2743
+ try {
2744
+ ast = this.parse(value).ast;
2745
+ } catch {
2746
+ return countLeafTokens(value);
2747
+ }
2748
+ }
2749
+
2750
+ const countLeaves = (node) => {
2751
+ if (!node || typeof node !== "object") return 0;
2752
+
2753
+ switch (node.type) {
2754
+ case "Literal":
2755
+ case "ImaginaryLiteral":
2756
+ case "UnitLiteral":
2757
+ case "Identifier":
2758
+ return 1;
2759
+ default:
2760
+ return Object.values(node).reduce((sum, child) => {
2761
+ if (Array.isArray(child)) {
2762
+ return sum + child.reduce((inner, item) => inner + countLeaves(item), 0);
2763
+ }
2764
+
2765
+ return sum + countLeaves(child);
2766
+ }, 0);
2767
+ }
2768
+ };
2769
+
2770
+ return countLeaves(ast);
2771
+ });
2772
+ this.addFunction("matrix", (value) => wrapDenseMatrix(value));
2773
+ this.addFunction("sparse", (value) => wrapDenseMatrix(value));
2774
+ this.addFunction("rationalize", (expression, withDetails = false) => {
2775
+ if (typeof expression !== "string") {
2776
+ throw new Error("rationalize() expects an expression string");
2777
+ }
2778
+
2779
+ const normalizedExpression = expression
2780
+ .replace(/\s+/g, "")
2781
+ .replace(/(\d)([a-zA-Z(])/g, "$1*$2")
2782
+ .replace(/([a-zA-Z)])(\d)/g, "$1*$2");
2783
+
2784
+ const polyKey = (powers) => JSON.stringify(Object.entries(powers).sort(([a], [b]) => a.localeCompare(b)));
2785
+ const keyToPowers = (key) => Object.fromEntries(JSON.parse(key));
2786
+ const constPoly = (value) => new Map([[polyKey({}), value]]);
2787
+ const varPoly = (name) => new Map([[polyKey({ [name]: 1 }), 1]]);
2788
+ const cleanPoly = (poly) => new Map([...poly.entries()].filter(([, coeff]) => coeff !== 0));
2789
+ const addPoly = (a, b, sign = 1) => {
2790
+ const result = new Map(a);
2791
+ for (const [key, coeff] of b.entries()) {
2792
+ result.set(key, (result.get(key) || 0) + (sign * coeff));
2793
+ }
2794
+ return cleanPoly(result);
2795
+ };
2796
+ const multiplyPoly = (a, b) => {
2797
+ const result = new Map();
2798
+ for (const [keyA, coeffA] of a.entries()) {
2799
+ const powersA = keyToPowers(keyA);
2800
+ for (const [keyB, coeffB] of b.entries()) {
2801
+ const powersB = keyToPowers(keyB);
2802
+ const merged = { ...powersA };
2803
+ for (const [name, power] of Object.entries(powersB)) {
2804
+ merged[name] = (merged[name] || 0) + power;
2805
+ }
2806
+ const key = polyKey(merged);
2807
+ result.set(key, (result.get(key) || 0) + (coeffA * coeffB));
2808
+ }
2809
+ }
2810
+ return cleanPoly(result);
2811
+ };
2812
+ const powPoly = (poly, exponent) => {
2813
+ let result = constPoly(1);
2814
+ for (let index = 0; index < exponent; index++) {
2815
+ result = multiplyPoly(result, poly);
2816
+ }
2817
+ return result;
2818
+ };
2819
+ const rational = (num, den = constPoly(1)) => ({ num, den });
2820
+ const addRat = (a, b, sign = 1) => rational(
2821
+ addPoly(
2822
+ multiplyPoly(a.num, b.den),
2823
+ multiplyPoly(b.num, a.den),
2824
+ sign
2825
+ ),
2826
+ multiplyPoly(a.den, b.den)
2827
+ );
2828
+ const mulRat = (a, b) => rational(multiplyPoly(a.num, b.num), multiplyPoly(a.den, b.den));
2829
+ const divRat = (a, b) => rational(multiplyPoly(a.num, b.den), multiplyPoly(a.den, b.num));
2830
+ const negRat = (value) => rational(addPoly(new Map(), value.num, -1), value.den);
2831
+ const astToRat = (node) => {
2832
+ switch (node.type) {
2833
+ case "Literal":
2834
+ return rational(constPoly(node.value));
2835
+ case "Identifier":
2836
+ return rational(varPoly(node.name));
2837
+ case "UnaryExpression":
2838
+ if (node.operator === "-") return negRat(astToRat(node.argument));
2839
+ throw new Error("Unsupported unary operator");
2840
+ case "BinaryExpression": {
2841
+ const left = astToRat(node.left);
2842
+ const right = astToRat(node.right);
2843
+ switch (node.operator) {
2844
+ case "+": return addRat(left, right);
2845
+ case "-": return addRat(left, right, -1);
2846
+ case "*": return mulRat(left, right);
2847
+ case "/": return divRat(left, right);
2848
+ case "^": {
2849
+ if (node.right.type !== "Literal" || !Number.isInteger(node.right.value) || node.right.value < 0) {
2850
+ throw new Error("Unsupported exponent");
2851
+ }
2852
+ return rational(
2853
+ powPoly(left.num, node.right.value),
2854
+ powPoly(left.den, node.right.value)
2855
+ );
2856
+ }
2857
+ default:
2858
+ throw new Error("Unsupported operator in rationalize()");
2859
+ }
2860
+ }
2861
+ default:
2862
+ throw new Error("Unsupported expression in rationalize()");
2863
+ }
2864
+ };
2865
+ const formatPoly = (poly) => {
2866
+ const entries = [...poly.entries()]
2867
+ .filter(([, coeff]) => coeff !== 0)
2868
+ .sort(([keyA], [keyB]) => {
2869
+ const powersA = keyToPowers(keyA);
2870
+ const powersB = keyToPowers(keyB);
2871
+ const firstVarA = Object.keys(powersA).sort()[0] || "";
2872
+ const firstVarB = Object.keys(powersB).sort()[0] || "";
2873
+
2874
+ if (firstVarA !== firstVarB) {
2875
+ return firstVarA.localeCompare(firstVarB);
2876
+ }
2877
+
2878
+ const degreeA = Object.values(powersA).reduce((sum, value) => sum + value, 0);
2879
+ const degreeB = Object.values(powersB).reduce((sum, value) => sum + value, 0);
2880
+ return degreeB - degreeA;
2881
+ });
2882
+
2883
+ if (!entries.length) return "0";
2884
+
2885
+ return entries.map(([key, coeff], index) => {
2886
+ const powers = keyToPowers(key);
2887
+ const absCoeff = Math.abs(coeff);
2888
+ const variablePart = Object.entries(powers)
2889
+ .map(([name, power]) => power === 1 ? name : `${name} ^ ${power}`)
2890
+ .join(" * ");
2891
+ let body = variablePart;
2892
+
2893
+ if (!body) {
2894
+ body = `${absCoeff}`;
2895
+ } else if (absCoeff !== 1) {
2896
+ body = `${absCoeff} * ${body}`;
2897
+ }
2898
+
2899
+ if (index === 0) {
2900
+ return coeff < 0 ? `- ${body}`.replace("- ", "-") : body;
2901
+ }
2902
+
2903
+ return coeff < 0 ? `- ${body}` : `+ ${body}`;
2904
+ }).join(" ");
2905
+ };
2906
+
2907
+ const ast = this.parse(normalizedExpression).ast;
2908
+ const result = astToRat(ast);
2909
+ const numerator = formatPoly(result.num);
2910
+ const denominator = formatPoly(result.den);
2911
+ const variableSet = new Set();
2912
+
2913
+ for (const poly of [result.num, result.den]) {
2914
+ for (const key of poly.keys()) {
2915
+ for (const name of Object.keys(keyToPowers(key))) {
2916
+ variableSet.add(name);
2917
+ }
2918
+ }
2919
+ }
2920
+
2921
+ if (!withDetails) {
2922
+ return `(${numerator}) / (${denominator})`;
2923
+ }
2924
+
2925
+ return {
2926
+ numerator,
2927
+ denominator,
2928
+ coefficients: [],
2929
+ variables: [...variableSet].sort(),
2930
+ expression: `(${numerator}) / (${denominator})`
2931
+ };
2932
+ });
2933
+ }
2934
+
2935
+ setVariable(name, value) {
2936
+ this.variables.set(name, value);
2937
+ }
2938
+
2939
+ getVariable(name) {
2940
+ return this.variables.get(name);
2941
+ }
2942
+
2943
+ addFunction(name, fn) {
2944
+ this.functions.register(name, fn);
2945
+ }
2946
+
2947
+ _createContext() {
2948
+ return createContext({
2949
+ functions: this.functions,
2950
+ variables: this.variables,
2951
+ units: this.units,
2952
+ evaluate: this.evaluate.bind(this)
2953
+ });
2954
+ }
2955
+
2956
+ tokenize(expr) {
2957
+ if (typeof expr !== "string") {
2958
+ throw new Error("Expression must be a string");
2959
+ }
2960
+ return tokenize(expr, this._createContext());
2961
+ }
2962
+
2963
+ parse(expr) {
2964
+ const tokens = this.tokenize(expr);
2965
+ const ast = buildAST(tokens);
2966
+ return { tokens, ast };
2967
+ }
2968
+
2969
+ evaluate(expr) {
2970
+ const { ast } = this.parse(expr);
2971
+ return formatResult(evaluateAST(
2972
+ ast,
2973
+ this._createContext()
2974
+ ));
2975
+ }
2976
+
2977
+ compile(expr) {
2978
+ if (this._cache.has(expr)) {
2979
+ return this._cache.get(expr);
2980
+ }
2981
+
2982
+ const { ast } = this.parse(expr);
2983
+
2984
+ const compiledFn = (scope = {}) => {
2985
+ const baseContext = this._createContext();
2986
+ const scopedContext = baseContext.withScope(scope);
2987
+ return formatResult(evaluateAST(ast, scopedContext));
2988
+ };
2989
+
2990
+ this._cache.set(expr, compiledFn);
2991
+ return compiledFn;
2992
+ }
2993
+
2994
+ clearCache() {
2995
+ this._cache.clear();
2996
+ }
2997
+
508
2998
  }
509
2999
 
510
- export { ViewPoint as Exprify, externalFunctions, internalFunctions, mathOperations, variablesDB };
3000
+ export { exprify as default };
511
3001