exprify 1.0.0 → 1.0.1

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