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