@devmm/puredocs-excel-formula 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/index.cjs +1941 -46
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +234 -7
- package/dist/index.d.ts +234 -7
- package/dist/index.js +1933 -48
- package/dist/index.js.map +1 -1
- package/package.json +45 -45
- package/LICENSE +0 -21
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { toOADate, fromOADate, parseCellRef, cellRefFromRowCol } from '@devmm/puredocs-excel';
|
|
1
|
+
import { toOADate, fromOADate, columnLetter, parseCellRef, cellRefFromRowCol } from '@devmm/puredocs-excel';
|
|
2
2
|
|
|
3
3
|
var __typeError = (msg) => {
|
|
4
4
|
throw TypeError(msg);
|
|
@@ -29,15 +29,21 @@ var FormulaError = /* @__PURE__ */ ((FormulaError2) => {
|
|
|
29
29
|
FormulaError2[FormulaError2["Spill"] = 9] = "Spill";
|
|
30
30
|
return FormulaError2;
|
|
31
31
|
})(FormulaError || {});
|
|
32
|
+
var TailCall = class {
|
|
33
|
+
constructor(lambda, args) {
|
|
34
|
+
this.lambda = lambda;
|
|
35
|
+
this.args = args;
|
|
36
|
+
}
|
|
37
|
+
};
|
|
32
38
|
var _num, _obj;
|
|
33
39
|
var _FormulaValue = class _FormulaValue {
|
|
34
|
-
constructor(kind,
|
|
40
|
+
constructor(kind, num5 = 0, obj, errorCode = 0 /* None */) {
|
|
35
41
|
/** Numeric payload (also used for boolean: 1=true, 0=false). */
|
|
36
42
|
__privateAdd(this, _num);
|
|
37
|
-
/** String or
|
|
43
|
+
/** String, ArrayValue, or LambdaLike payload. */
|
|
38
44
|
__privateAdd(this, _obj);
|
|
39
45
|
this.kind = kind;
|
|
40
|
-
__privateSet(this, _num,
|
|
46
|
+
__privateSet(this, _num, num5);
|
|
41
47
|
__privateSet(this, _obj, obj);
|
|
42
48
|
this.errorCode = errorCode;
|
|
43
49
|
}
|
|
@@ -77,6 +83,9 @@ var _FormulaValue = class _FormulaValue {
|
|
|
77
83
|
static array(a) {
|
|
78
84
|
return new _FormulaValue("array", 0, a);
|
|
79
85
|
}
|
|
86
|
+
static lambda(fn) {
|
|
87
|
+
return new _FormulaValue("lambda", 0, fn);
|
|
88
|
+
}
|
|
80
89
|
// ── Type checks ──────────────────────────────────────────────────────────
|
|
81
90
|
get isBlank() {
|
|
82
91
|
return this.kind === "blank";
|
|
@@ -96,6 +105,9 @@ var _FormulaValue = class _FormulaValue {
|
|
|
96
105
|
get isArray() {
|
|
97
106
|
return this.kind === "array";
|
|
98
107
|
}
|
|
108
|
+
get isLambda() {
|
|
109
|
+
return this.kind === "lambda";
|
|
110
|
+
}
|
|
99
111
|
get isNumeric() {
|
|
100
112
|
return this.kind === "number" || this.kind === "boolean" || this.kind === "blank";
|
|
101
113
|
}
|
|
@@ -112,6 +124,9 @@ var _FormulaValue = class _FormulaValue {
|
|
|
112
124
|
get arrayVal() {
|
|
113
125
|
return __privateGet(this, _obj) ?? ArrayValue.empty;
|
|
114
126
|
}
|
|
127
|
+
get lambdaVal() {
|
|
128
|
+
return __privateGet(this, _obj);
|
|
129
|
+
}
|
|
115
130
|
// ── Coercion (Excel semantics, no exceptions) ─────────────────────────────
|
|
116
131
|
coerceToNumber() {
|
|
117
132
|
switch (this.kind) {
|
|
@@ -179,6 +194,8 @@ var _FormulaValue = class _FormulaValue {
|
|
|
179
194
|
return "";
|
|
180
195
|
case "error":
|
|
181
196
|
return _FormulaValue.errorToString(this.errorCode);
|
|
197
|
+
case "lambda":
|
|
198
|
+
return _FormulaValue.errorToString(8 /* Calc */);
|
|
182
199
|
default:
|
|
183
200
|
return "";
|
|
184
201
|
}
|
|
@@ -276,6 +293,8 @@ var _FormulaValue = class _FormulaValue {
|
|
|
276
293
|
return _FormulaValue.errorToString(this.errorCode);
|
|
277
294
|
case "array":
|
|
278
295
|
return this.arrayVal.toObjectArray();
|
|
296
|
+
case "lambda":
|
|
297
|
+
return _FormulaValue.errorToString(8 /* Calc */);
|
|
279
298
|
default:
|
|
280
299
|
return null;
|
|
281
300
|
}
|
|
@@ -424,10 +443,11 @@ var TokenType = /* @__PURE__ */ ((TokenType2) => {
|
|
|
424
443
|
TokenType2[TokenType2["GreaterThanOrEqual"] = 21] = "GreaterThanOrEqual";
|
|
425
444
|
TokenType2[TokenType2["SheetReference"] = 22] = "SheetReference";
|
|
426
445
|
TokenType2[TokenType2["NamedRange"] = 23] = "NamedRange";
|
|
427
|
-
TokenType2[TokenType2["
|
|
428
|
-
TokenType2[TokenType2["
|
|
429
|
-
TokenType2[TokenType2["
|
|
430
|
-
TokenType2[TokenType2["
|
|
446
|
+
TokenType2[TokenType2["SpillReference"] = 24] = "SpillReference";
|
|
447
|
+
TokenType2[TokenType2["Exclamation"] = 25] = "Exclamation";
|
|
448
|
+
TokenType2[TokenType2["AtSign"] = 26] = "AtSign";
|
|
449
|
+
TokenType2[TokenType2["ErrorLiteral"] = 27] = "ErrorLiteral";
|
|
450
|
+
TokenType2[TokenType2["EOF"] = 28] = "EOF";
|
|
431
451
|
return TokenType2;
|
|
432
452
|
})(TokenType || {});
|
|
433
453
|
function makeToken(type, value2, position) {
|
|
@@ -470,7 +490,7 @@ var FormulaLexer = class {
|
|
|
470
490
|
const token = __privateMethod(this, _FormulaLexer_instances, readNextToken_fn).call(this);
|
|
471
491
|
if (token) tokens.push(token);
|
|
472
492
|
}
|
|
473
|
-
tokens.push(makeToken(
|
|
493
|
+
tokens.push(makeToken(28 /* EOF */, "", __privateGet(this, _pos)));
|
|
474
494
|
return tokens;
|
|
475
495
|
}
|
|
476
496
|
};
|
|
@@ -524,7 +544,7 @@ readErrorLiteral_fn = function() {
|
|
|
524
544
|
if (!KNOWN_ERRORS.has(upper2)) {
|
|
525
545
|
throw new FormulaException(`Unknown error literal "${raw}" at position ${start}.`);
|
|
526
546
|
}
|
|
527
|
-
return makeToken(
|
|
547
|
+
return makeToken(27 /* ErrorLiteral */, upper2, start);
|
|
528
548
|
};
|
|
529
549
|
readQuotedSheetRef_fn = function() {
|
|
530
550
|
const start = __privateWrapper(this, _pos)._++;
|
|
@@ -603,7 +623,13 @@ readIdentifier_fn = function() {
|
|
|
603
623
|
return makeToken(5 /* Function */, upper2, start);
|
|
604
624
|
}
|
|
605
625
|
const stripped = raw.replace(/\$/g, "");
|
|
606
|
-
if (isCellRef(stripped))
|
|
626
|
+
if (isCellRef(stripped)) {
|
|
627
|
+
if (__privateGet(this, _formula)[__privateGet(this, _pos)] === "#") {
|
|
628
|
+
__privateWrapper(this, _pos)._++;
|
|
629
|
+
return makeToken(24 /* SpillReference */, stripped, start);
|
|
630
|
+
}
|
|
631
|
+
return makeToken(3 /* CellReference */, stripped, start);
|
|
632
|
+
}
|
|
607
633
|
return makeToken(23 /* NamedRange */, raw, start);
|
|
608
634
|
};
|
|
609
635
|
readCellRefChars_fn = function() {
|
|
@@ -646,9 +672,9 @@ readOperator_fn = function() {
|
|
|
646
672
|
case "=":
|
|
647
673
|
return makeToken(16 /* Equal */, "=", start);
|
|
648
674
|
case "@":
|
|
649
|
-
return makeToken(
|
|
675
|
+
return makeToken(26 /* AtSign */, "@", start);
|
|
650
676
|
case "!":
|
|
651
|
-
return makeToken(
|
|
677
|
+
return makeToken(25 /* Exclamation */, "!", start);
|
|
652
678
|
case "<":
|
|
653
679
|
if (__privateGet(this, _formula)[__privateGet(this, _pos)] === ">") {
|
|
654
680
|
__privateWrapper(this, _pos)._++;
|
|
@@ -685,6 +711,15 @@ function isCellRef(s) {
|
|
|
685
711
|
|
|
686
712
|
// src/formula-node.ts
|
|
687
713
|
var FormulaNode = class {
|
|
714
|
+
/**
|
|
715
|
+
* Evaluates this node in tail position. Returns a TailCall when the node's
|
|
716
|
+
* value is a call to a lambda in tail position (so the caller's trampoline can
|
|
717
|
+
* iterate without growing the stack); otherwise the final value. The default
|
|
718
|
+
* is a plain evaluate — only control-flow and call nodes override it.
|
|
719
|
+
*/
|
|
720
|
+
evaluateTail(ctx) {
|
|
721
|
+
return this.evaluate(ctx);
|
|
722
|
+
}
|
|
688
723
|
};
|
|
689
724
|
var NumberNode = class extends FormulaNode {
|
|
690
725
|
constructor(value2) {
|
|
@@ -776,6 +811,15 @@ var NamedRangeNode = class extends FormulaNode {
|
|
|
776
811
|
return ctx.resolveNamedRange(this.name);
|
|
777
812
|
}
|
|
778
813
|
};
|
|
814
|
+
var SpillReferenceNode = class extends FormulaNode {
|
|
815
|
+
constructor(anchorRef) {
|
|
816
|
+
super();
|
|
817
|
+
this.anchorRef = anchorRef;
|
|
818
|
+
}
|
|
819
|
+
evaluate(ctx) {
|
|
820
|
+
return ctx.resolveSpillRange(this.anchorRef);
|
|
821
|
+
}
|
|
822
|
+
};
|
|
779
823
|
var BinaryOperator = /* @__PURE__ */ ((BinaryOperator2) => {
|
|
780
824
|
BinaryOperator2[BinaryOperator2["Add"] = 0] = "Add";
|
|
781
825
|
BinaryOperator2[BinaryOperator2["Subtract"] = 1] = "Subtract";
|
|
@@ -899,10 +943,85 @@ var FunctionCallNode = class extends FormulaNode {
|
|
|
899
943
|
evaluate(ctx) {
|
|
900
944
|
return ctx.evaluateFunction(this.functionName, this.args);
|
|
901
945
|
}
|
|
946
|
+
evaluateTail(ctx) {
|
|
947
|
+
const name = this.functionName;
|
|
948
|
+
const a = this.args;
|
|
949
|
+
switch (name) {
|
|
950
|
+
case "IF": {
|
|
951
|
+
const cond = a[0].evaluate(ctx);
|
|
952
|
+
if (cond.isError) return cond;
|
|
953
|
+
const b = cond.coerceToBool();
|
|
954
|
+
if (b.isError) return b;
|
|
955
|
+
if (b.booleanValue) return a[1].evaluateTail(ctx);
|
|
956
|
+
return a.length > 2 ? a[2].evaluateTail(ctx) : FormulaValue.false_;
|
|
957
|
+
}
|
|
958
|
+
case "IFS": {
|
|
959
|
+
for (let i = 0; i + 1 < a.length; i += 2) {
|
|
960
|
+
const cond = a[i].evaluate(ctx);
|
|
961
|
+
if (cond.isError) return cond;
|
|
962
|
+
const b = cond.coerceToBool();
|
|
963
|
+
if (b.isError) return b;
|
|
964
|
+
if (b.booleanValue) return a[i + 1].evaluateTail(ctx);
|
|
965
|
+
}
|
|
966
|
+
return FormulaValue.errorNA;
|
|
967
|
+
}
|
|
968
|
+
case "IFERROR": {
|
|
969
|
+
const v = a[0].evaluate(ctx);
|
|
970
|
+
return v.isError ? a[1].evaluateTail(ctx) : v;
|
|
971
|
+
}
|
|
972
|
+
case "IFNA": {
|
|
973
|
+
const v = a[0].evaluate(ctx);
|
|
974
|
+
return v.isError && v.errorCode === 7 /* NA */ ? a[1].evaluateTail(ctx) : v;
|
|
975
|
+
}
|
|
976
|
+
case "LET": {
|
|
977
|
+
if (a.length < 3 || a.length % 2 === 0) break;
|
|
978
|
+
const bindings = /* @__PURE__ */ new Map();
|
|
979
|
+
ctx.pushScope(bindings);
|
|
980
|
+
try {
|
|
981
|
+
for (let i = 0; i < a.length - 1; i += 2) {
|
|
982
|
+
const nn = a[i];
|
|
983
|
+
if (!(nn instanceof NamedRangeNode)) return FormulaValue.errorValue;
|
|
984
|
+
const val = a[i + 1].evaluate(ctx);
|
|
985
|
+
if (val.isError) return val;
|
|
986
|
+
bindings.set(nn.name.toUpperCase(), val);
|
|
987
|
+
}
|
|
988
|
+
return a[a.length - 1].evaluateTail(ctx);
|
|
989
|
+
} finally {
|
|
990
|
+
ctx.popScope();
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
if (!ctx.hasFunction(name)) {
|
|
995
|
+
const named = ctx.resolveNamedRange(name);
|
|
996
|
+
if (named.isLambda) {
|
|
997
|
+
return new TailCall(named.lambdaVal, a.map((arg2) => arg2.evaluate(ctx)));
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
return this.evaluate(ctx);
|
|
1001
|
+
}
|
|
1002
|
+
};
|
|
1003
|
+
var CallNode = class extends FormulaNode {
|
|
1004
|
+
constructor(callee, args) {
|
|
1005
|
+
super();
|
|
1006
|
+
this.callee = callee;
|
|
1007
|
+
this.args = args;
|
|
1008
|
+
}
|
|
1009
|
+
evaluate(ctx) {
|
|
1010
|
+
const fn = this.callee.evaluate(ctx);
|
|
1011
|
+
if (fn.isError) return fn;
|
|
1012
|
+
if (!fn.isLambda) return FormulaValue.errorValue;
|
|
1013
|
+
return fn.lambdaVal.call(this.args.map((a) => a.evaluate(ctx)));
|
|
1014
|
+
}
|
|
1015
|
+
evaluateTail(ctx) {
|
|
1016
|
+
const fn = this.callee.evaluate(ctx);
|
|
1017
|
+
if (fn.isError) return fn;
|
|
1018
|
+
if (!fn.isLambda) return FormulaValue.errorValue;
|
|
1019
|
+
return new TailCall(fn.lambdaVal, this.args.map((a) => a.evaluate(ctx)));
|
|
1020
|
+
}
|
|
902
1021
|
};
|
|
903
1022
|
|
|
904
1023
|
// src/formula-parser.ts
|
|
905
|
-
var _tokens, _pos2, _FormulaParser_instances, current_get, advance_fn, expect_fn, parseComparison_fn, parseConcatenation_fn, parseAddSub_fn, parseMulDiv_fn, parseUnary_fn, parsePower_fn, parsePercent_fn, parsePrimary_fn, parseFunction_fn;
|
|
1024
|
+
var _tokens, _pos2, _FormulaParser_instances, current_get, advance_fn, expect_fn, parseComparison_fn, parseConcatenation_fn, parseAddSub_fn, parseMulDiv_fn, parseUnary_fn, parsePower_fn, parsePercent_fn, parsePostfix_fn, parsePrimary_fn, parseFunction_fn, parseArgList_fn;
|
|
906
1025
|
var FormulaParser = class {
|
|
907
1026
|
constructor(tokens) {
|
|
908
1027
|
__privateAdd(this, _FormulaParser_instances);
|
|
@@ -913,7 +1032,7 @@ var FormulaParser = class {
|
|
|
913
1032
|
parse() {
|
|
914
1033
|
__privateSet(this, _pos2, 0);
|
|
915
1034
|
const node = __privateMethod(this, _FormulaParser_instances, parseComparison_fn).call(this);
|
|
916
|
-
if (__privateGet(this, _FormulaParser_instances, current_get).type !==
|
|
1035
|
+
if (__privateGet(this, _FormulaParser_instances, current_get).type !== 28 /* EOF */) {
|
|
917
1036
|
throw new FormulaException(
|
|
918
1037
|
`Unexpected token '${__privateGet(this, _FormulaParser_instances, current_get).value}' at position ${__privateGet(this, _FormulaParser_instances, current_get).position}.`
|
|
919
1038
|
);
|
|
@@ -925,7 +1044,7 @@ _tokens = new WeakMap();
|
|
|
925
1044
|
_pos2 = new WeakMap();
|
|
926
1045
|
_FormulaParser_instances = new WeakSet();
|
|
927
1046
|
current_get = function() {
|
|
928
|
-
return __privateGet(this, _tokens)[__privateGet(this, _pos2)] ?? { type:
|
|
1047
|
+
return __privateGet(this, _tokens)[__privateGet(this, _pos2)] ?? { type: 28 /* EOF */, value: "", position: -1 };
|
|
929
1048
|
};
|
|
930
1049
|
advance_fn = function() {
|
|
931
1050
|
const t = __privateGet(this, _FormulaParser_instances, current_get);
|
|
@@ -990,7 +1109,7 @@ parseUnary_fn = function() {
|
|
|
990
1109
|
__privateMethod(this, _FormulaParser_instances, advance_fn).call(this);
|
|
991
1110
|
return new UnaryOpNode(1 /* Plus */, __privateMethod(this, _FormulaParser_instances, parsePower_fn).call(this));
|
|
992
1111
|
}
|
|
993
|
-
if (__privateGet(this, _FormulaParser_instances, current_get).type ===
|
|
1112
|
+
if (__privateGet(this, _FormulaParser_instances, current_get).type === 26 /* AtSign */) {
|
|
994
1113
|
__privateMethod(this, _FormulaParser_instances, advance_fn).call(this);
|
|
995
1114
|
return new ImplicitIntersectionNode(__privateMethod(this, _FormulaParser_instances, parsePower_fn).call(this));
|
|
996
1115
|
}
|
|
@@ -1005,13 +1124,22 @@ parsePower_fn = function() {
|
|
|
1005
1124
|
return left2;
|
|
1006
1125
|
};
|
|
1007
1126
|
parsePercent_fn = function() {
|
|
1008
|
-
let node = __privateMethod(this, _FormulaParser_instances,
|
|
1127
|
+
let node = __privateMethod(this, _FormulaParser_instances, parsePostfix_fn).call(this);
|
|
1009
1128
|
while (__privateGet(this, _FormulaParser_instances, current_get).type === 14 /* Percent */) {
|
|
1010
1129
|
__privateMethod(this, _FormulaParser_instances, advance_fn).call(this);
|
|
1011
1130
|
node = new UnaryOpNode(2 /* Percent */, node);
|
|
1012
1131
|
}
|
|
1013
1132
|
return node;
|
|
1014
1133
|
};
|
|
1134
|
+
/** Handles postfix call syntax on an expression, e.g. LAMBDA(x,x+1)(5). */
|
|
1135
|
+
parsePostfix_fn = function() {
|
|
1136
|
+
let node = __privateMethod(this, _FormulaParser_instances, parsePrimary_fn).call(this);
|
|
1137
|
+
while (__privateGet(this, _FormulaParser_instances, current_get).type === 6 /* LeftParen */) {
|
|
1138
|
+
__privateMethod(this, _FormulaParser_instances, advance_fn).call(this);
|
|
1139
|
+
node = new CallNode(node, __privateMethod(this, _FormulaParser_instances, parseArgList_fn).call(this));
|
|
1140
|
+
}
|
|
1141
|
+
return node;
|
|
1142
|
+
};
|
|
1015
1143
|
parsePrimary_fn = function() {
|
|
1016
1144
|
const token = __privateGet(this, _FormulaParser_instances, current_get);
|
|
1017
1145
|
switch (token.type) {
|
|
@@ -1027,7 +1155,7 @@ parsePrimary_fn = function() {
|
|
|
1027
1155
|
case 2 /* Boolean */:
|
|
1028
1156
|
__privateMethod(this, _FormulaParser_instances, advance_fn).call(this);
|
|
1029
1157
|
return new BooleanNode(token.value === "TRUE");
|
|
1030
|
-
case
|
|
1158
|
+
case 27 /* ErrorLiteral */:
|
|
1031
1159
|
__privateMethod(this, _FormulaParser_instances, advance_fn).call(this);
|
|
1032
1160
|
return new ErrorNode(FormulaValue.error(FormulaValue.errorFromString(token.value)));
|
|
1033
1161
|
case 3 /* CellReference */: {
|
|
@@ -1054,6 +1182,9 @@ parsePrimary_fn = function() {
|
|
|
1054
1182
|
case 23 /* NamedRange */:
|
|
1055
1183
|
__privateMethod(this, _FormulaParser_instances, advance_fn).call(this);
|
|
1056
1184
|
return new NamedRangeNode(token.value);
|
|
1185
|
+
case 24 /* SpillReference */:
|
|
1186
|
+
__privateMethod(this, _FormulaParser_instances, advance_fn).call(this);
|
|
1187
|
+
return new SpillReferenceNode(token.value);
|
|
1057
1188
|
case 5 /* Function */:
|
|
1058
1189
|
return __privateMethod(this, _FormulaParser_instances, parseFunction_fn).call(this);
|
|
1059
1190
|
case 6 /* LeftParen */: {
|
|
@@ -1071,6 +1202,10 @@ parsePrimary_fn = function() {
|
|
|
1071
1202
|
parseFunction_fn = function() {
|
|
1072
1203
|
const nameToken = __privateMethod(this, _FormulaParser_instances, advance_fn).call(this);
|
|
1073
1204
|
__privateMethod(this, _FormulaParser_instances, expect_fn).call(this, 6 /* LeftParen */);
|
|
1205
|
+
return new FunctionCallNode(nameToken.value.toUpperCase(), __privateMethod(this, _FormulaParser_instances, parseArgList_fn).call(this));
|
|
1206
|
+
};
|
|
1207
|
+
/** Parses a comma-separated argument list up to and including the ')'. */
|
|
1208
|
+
parseArgList_fn = function() {
|
|
1074
1209
|
const args = [];
|
|
1075
1210
|
if (__privateGet(this, _FormulaParser_instances, current_get).type !== 7 /* RightParen */) {
|
|
1076
1211
|
if (__privateGet(this, _FormulaParser_instances, current_get).type === 8 /* Comma */) {
|
|
@@ -1088,7 +1223,7 @@ parseFunction_fn = function() {
|
|
|
1088
1223
|
}
|
|
1089
1224
|
}
|
|
1090
1225
|
__privateMethod(this, _FormulaParser_instances, expect_fn).call(this, 7 /* RightParen */);
|
|
1091
|
-
return
|
|
1226
|
+
return args;
|
|
1092
1227
|
};
|
|
1093
1228
|
function comparisonOp(type) {
|
|
1094
1229
|
switch (type) {
|
|
@@ -1119,10 +1254,14 @@ function registerMath(r) {
|
|
|
1119
1254
|
r.register("COUNTA", countA, 1);
|
|
1120
1255
|
r.register("COUNTBLANK", countBlank, 1, 1);
|
|
1121
1256
|
r.register("COUNTIF", countIf, 2, 2);
|
|
1257
|
+
r.register("COUNTIFS", countIfs, 2);
|
|
1122
1258
|
r.register("SUMIF", sumIf, 2, 3);
|
|
1259
|
+
r.register("SUMIFS", sumIfs, 3);
|
|
1123
1260
|
r.register("AVERAGEIF", averageIf, 2, 3);
|
|
1261
|
+
r.register("AVERAGEIFS", averageIfs, 3);
|
|
1124
1262
|
r.register("PRODUCT", product, 1);
|
|
1125
1263
|
r.register("SUMPRODUCT", sumProduct, 1);
|
|
1264
|
+
r.register("SUMSQ", sumSq, 1);
|
|
1126
1265
|
r.register("ABS", abs, 1, 1);
|
|
1127
1266
|
r.register("ROUND", round, 2, 2);
|
|
1128
1267
|
r.register("ROUNDUP", roundUp, 2, 2);
|
|
@@ -1147,6 +1286,114 @@ function registerMath(r) {
|
|
|
1147
1286
|
r.register("EXP", exp, 1, 1);
|
|
1148
1287
|
r.register("FACT", fact, 1, 1);
|
|
1149
1288
|
r.register("COMBIN", combin, 2, 2);
|
|
1289
|
+
r.register("SIN", unary(Math.sin), 1, 1);
|
|
1290
|
+
r.register("COS", unary(Math.cos), 1, 1);
|
|
1291
|
+
r.register("TAN", unary(Math.tan), 1, 1);
|
|
1292
|
+
r.register("ASIN", asin, 1, 1);
|
|
1293
|
+
r.register("ACOS", acos, 1, 1);
|
|
1294
|
+
r.register("ATAN", unary(Math.atan), 1, 1);
|
|
1295
|
+
r.register("ATAN2", atan2, 2, 2);
|
|
1296
|
+
r.register("SINH", unary(Math.sinh), 1, 1);
|
|
1297
|
+
r.register("COSH", unary(Math.cosh), 1, 1);
|
|
1298
|
+
r.register("TANH", unary(Math.tanh), 1, 1);
|
|
1299
|
+
r.register("DEGREES", unary((r2d) => r2d * 180 / Math.PI), 1, 1);
|
|
1300
|
+
r.register("RADIANS", unary((d) => d * Math.PI / 180), 1, 1);
|
|
1301
|
+
}
|
|
1302
|
+
function valueAt(v, i) {
|
|
1303
|
+
return v.isArray ? v.arrayVal.getFlat(i) : v;
|
|
1304
|
+
}
|
|
1305
|
+
function lengthOf(v) {
|
|
1306
|
+
return v.isArray ? v.arrayVal.length : 1;
|
|
1307
|
+
}
|
|
1308
|
+
function computeIfsMask(a, c, startIdx, len2) {
|
|
1309
|
+
const mask = new Uint8Array(len2).fill(1);
|
|
1310
|
+
for (let p = startIdx; p + 1 < a.length; p += 2) {
|
|
1311
|
+
const cr = a[p].evaluate(c);
|
|
1312
|
+
if (cr.isError) return { ok: false, error: cr };
|
|
1313
|
+
const crit = a[p + 1].evaluate(c);
|
|
1314
|
+
if (crit.isError) return { ok: false, error: crit };
|
|
1315
|
+
const critText = crit.asText();
|
|
1316
|
+
for (let i = 0; i < len2; i++) {
|
|
1317
|
+
if (!mask[i]) continue;
|
|
1318
|
+
if (!FormulaHelper.matchesCriteria(valueAt(cr, i), critText)) mask[i] = 0;
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
return { ok: true, mask };
|
|
1322
|
+
}
|
|
1323
|
+
function sumIfs(a, c) {
|
|
1324
|
+
if (a.length < 3 || a.length % 2 === 0) return FormulaValue.errorValue;
|
|
1325
|
+
const sumRange = a[0].evaluate(c);
|
|
1326
|
+
if (sumRange.isError) return sumRange;
|
|
1327
|
+
const len2 = lengthOf(sumRange);
|
|
1328
|
+
const m = computeIfsMask(a, c, 1, len2);
|
|
1329
|
+
if (!m.ok) return m.error;
|
|
1330
|
+
let total = 0;
|
|
1331
|
+
for (let i = 0; i < len2; i++) {
|
|
1332
|
+
if (!m.mask[i]) continue;
|
|
1333
|
+
const r = valueAt(sumRange, i).tryAsDouble();
|
|
1334
|
+
if (r.ok) total += r.value;
|
|
1335
|
+
}
|
|
1336
|
+
return FormulaValue.number(total);
|
|
1337
|
+
}
|
|
1338
|
+
function countIfs(a, c) {
|
|
1339
|
+
if (a.length < 2 || a.length % 2 !== 0) return FormulaValue.errorValue;
|
|
1340
|
+
const first = a[0].evaluate(c);
|
|
1341
|
+
if (first.isError) return first;
|
|
1342
|
+
const len2 = lengthOf(first);
|
|
1343
|
+
const m = computeIfsMask(a, c, 0, len2);
|
|
1344
|
+
if (!m.ok) return m.error;
|
|
1345
|
+
let n = 0;
|
|
1346
|
+
for (let i = 0; i < len2; i++) if (m.mask[i]) n++;
|
|
1347
|
+
return FormulaValue.number(n);
|
|
1348
|
+
}
|
|
1349
|
+
function averageIfs(a, c) {
|
|
1350
|
+
if (a.length < 3 || a.length % 2 === 0) return FormulaValue.errorValue;
|
|
1351
|
+
const avgRange = a[0].evaluate(c);
|
|
1352
|
+
if (avgRange.isError) return avgRange;
|
|
1353
|
+
const len2 = lengthOf(avgRange);
|
|
1354
|
+
const m = computeIfsMask(a, c, 1, len2);
|
|
1355
|
+
if (!m.ok) return m.error;
|
|
1356
|
+
let total = 0, cnt = 0;
|
|
1357
|
+
for (let i = 0; i < len2; i++) {
|
|
1358
|
+
if (!m.mask[i]) continue;
|
|
1359
|
+
const r = valueAt(avgRange, i).tryAsDouble();
|
|
1360
|
+
if (r.ok) {
|
|
1361
|
+
total += r.value;
|
|
1362
|
+
cnt++;
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
return cnt === 0 ? FormulaValue.errorDiv0 : FormulaValue.number(total / cnt);
|
|
1366
|
+
}
|
|
1367
|
+
function sumSq(a, c) {
|
|
1368
|
+
const r = FormulaHelper.collectNumbers(a, c);
|
|
1369
|
+
if (!r.ok) return r.error;
|
|
1370
|
+
return FormulaValue.number(r.values.reduce((s, n) => s + n * n, 0));
|
|
1371
|
+
}
|
|
1372
|
+
function unary(fn) {
|
|
1373
|
+
return (a, c) => {
|
|
1374
|
+
const r = FormulaHelper.evalDouble(a[0], c);
|
|
1375
|
+
return r.ok ? FormulaValue.number(fn(r.value)) : r.error;
|
|
1376
|
+
};
|
|
1377
|
+
}
|
|
1378
|
+
function asin(a, c) {
|
|
1379
|
+
const r = FormulaHelper.evalDouble(a[0], c);
|
|
1380
|
+
if (!r.ok) return r.error;
|
|
1381
|
+
if (r.value < -1 || r.value > 1) return FormulaValue.errorNum;
|
|
1382
|
+
return FormulaValue.number(Math.asin(r.value));
|
|
1383
|
+
}
|
|
1384
|
+
function acos(a, c) {
|
|
1385
|
+
const r = FormulaHelper.evalDouble(a[0], c);
|
|
1386
|
+
if (!r.ok) return r.error;
|
|
1387
|
+
if (r.value < -1 || r.value > 1) return FormulaValue.errorNum;
|
|
1388
|
+
return FormulaValue.number(Math.acos(r.value));
|
|
1389
|
+
}
|
|
1390
|
+
function atan2(a, c) {
|
|
1391
|
+
const x = FormulaHelper.evalDouble(a[0], c);
|
|
1392
|
+
if (!x.ok) return x.error;
|
|
1393
|
+
const y = FormulaHelper.evalDouble(a[1], c);
|
|
1394
|
+
if (!y.ok) return y.error;
|
|
1395
|
+
if (x.value === 0 && y.value === 0) return FormulaValue.errorDiv0;
|
|
1396
|
+
return FormulaValue.number(Math.atan2(y.value, x.value));
|
|
1150
1397
|
}
|
|
1151
1398
|
function sum(a, c) {
|
|
1152
1399
|
const r = FormulaHelper.collectNumbers(a, c);
|
|
@@ -1265,7 +1512,7 @@ function product(a, c) {
|
|
|
1265
1512
|
return FormulaValue.number(r.values.reduce((p, n) => p * n, 1));
|
|
1266
1513
|
}
|
|
1267
1514
|
function sumProduct(a, c) {
|
|
1268
|
-
const arrays = a.map((
|
|
1515
|
+
const arrays = a.map((arg2) => arg2.evaluate(c));
|
|
1269
1516
|
for (const v of arrays) if (v.isError) return v;
|
|
1270
1517
|
const first = arrays[0];
|
|
1271
1518
|
const len2 = first.isArray ? first.arrayVal.length : 1;
|
|
@@ -1466,6 +1713,8 @@ function registerText(r) {
|
|
|
1466
1713
|
r.register("CHAR", char_, 1, 1);
|
|
1467
1714
|
r.register("CODE", code, 1, 1);
|
|
1468
1715
|
r.register("T", t_, 1, 1);
|
|
1716
|
+
r.register("TEXTBEFORE", textBefore, 2, 3);
|
|
1717
|
+
r.register("TEXTAFTER", textAfter, 2, 3);
|
|
1469
1718
|
}
|
|
1470
1719
|
function str(a, c, idx) {
|
|
1471
1720
|
const r = FormulaHelper.evalString(a[idx], c);
|
|
@@ -1594,8 +1843,8 @@ function replace(a, c) {
|
|
|
1594
1843
|
}
|
|
1595
1844
|
function concatenate(a, c) {
|
|
1596
1845
|
let result = "";
|
|
1597
|
-
for (const
|
|
1598
|
-
const v =
|
|
1846
|
+
for (const arg2 of a) {
|
|
1847
|
+
const v = arg2.evaluate(c);
|
|
1599
1848
|
if (v.isError) return v;
|
|
1600
1849
|
result += v.asText();
|
|
1601
1850
|
}
|
|
@@ -1722,6 +1971,45 @@ function t_(a, c) {
|
|
|
1722
1971
|
const v = a[0].evaluate(c);
|
|
1723
1972
|
return v.isText ? v : FormulaValue.emptyString;
|
|
1724
1973
|
}
|
|
1974
|
+
function textBefore(a, c) {
|
|
1975
|
+
return textSplitAt(a, c, "before");
|
|
1976
|
+
}
|
|
1977
|
+
function textAfter(a, c) {
|
|
1978
|
+
return textSplitAt(a, c, "after");
|
|
1979
|
+
}
|
|
1980
|
+
function textSplitAt(a, c, mode2) {
|
|
1981
|
+
const s = str(a, c, 0);
|
|
1982
|
+
if (!s.ok) return s.e;
|
|
1983
|
+
const d = str(a, c, 1);
|
|
1984
|
+
if (!d.ok) return d.e;
|
|
1985
|
+
let instance = 1;
|
|
1986
|
+
if (a.length > 2) {
|
|
1987
|
+
const r = num(a, c, 2);
|
|
1988
|
+
if (!r.ok) return r.e;
|
|
1989
|
+
instance = Math.trunc(r.n);
|
|
1990
|
+
}
|
|
1991
|
+
if (instance === 0) return FormulaValue.errorValue;
|
|
1992
|
+
const text = s.s;
|
|
1993
|
+
const delim = d.s;
|
|
1994
|
+
if (delim === "") {
|
|
1995
|
+
return FormulaValue.text(mode2 === "before" ? "" : text);
|
|
1996
|
+
}
|
|
1997
|
+
const positions = [];
|
|
1998
|
+
let from = 0;
|
|
1999
|
+
for (; ; ) {
|
|
2000
|
+
const idx = text.indexOf(delim, from);
|
|
2001
|
+
if (idx === -1) break;
|
|
2002
|
+
positions.push(idx);
|
|
2003
|
+
from = idx + delim.length;
|
|
2004
|
+
}
|
|
2005
|
+
if (positions.length === 0) return FormulaValue.errorNA;
|
|
2006
|
+
const nth = instance > 0 ? instance - 1 : positions.length + instance;
|
|
2007
|
+
if (nth < 0 || nth >= positions.length) return FormulaValue.errorNA;
|
|
2008
|
+
const pos = positions[nth];
|
|
2009
|
+
return FormulaValue.text(
|
|
2010
|
+
mode2 === "before" ? text.slice(0, pos) : text.slice(pos + delim.length)
|
|
2011
|
+
);
|
|
2012
|
+
}
|
|
1725
2013
|
|
|
1726
2014
|
// src/functions/logical-functions.ts
|
|
1727
2015
|
function registerLogical(r) {
|
|
@@ -1746,8 +2034,8 @@ function if_(a, c) {
|
|
|
1746
2034
|
}
|
|
1747
2035
|
function and(a, c) {
|
|
1748
2036
|
let hasValue = false;
|
|
1749
|
-
for (const
|
|
1750
|
-
const v =
|
|
2037
|
+
for (const arg2 of a) {
|
|
2038
|
+
const v = arg2.evaluate(c);
|
|
1751
2039
|
if (v.isError) return v;
|
|
1752
2040
|
if (v.isArray) {
|
|
1753
2041
|
for (const item of v.arrayVal.values()) {
|
|
@@ -1773,8 +2061,8 @@ function and(a, c) {
|
|
|
1773
2061
|
}
|
|
1774
2062
|
function or(a, c) {
|
|
1775
2063
|
let hasValue = false;
|
|
1776
|
-
for (const
|
|
1777
|
-
const v =
|
|
2064
|
+
for (const arg2 of a) {
|
|
2065
|
+
const v = arg2.evaluate(c);
|
|
1778
2066
|
if (v.isError) return v;
|
|
1779
2067
|
if (v.isArray) {
|
|
1780
2068
|
for (const item of v.arrayVal.values()) {
|
|
@@ -1807,8 +2095,8 @@ function not(a, c) {
|
|
|
1807
2095
|
}
|
|
1808
2096
|
function xor(a, c) {
|
|
1809
2097
|
let trueCount = 0;
|
|
1810
|
-
for (const
|
|
1811
|
-
const v =
|
|
2098
|
+
for (const arg2 of a) {
|
|
2099
|
+
const v = arg2.evaluate(c);
|
|
1812
2100
|
if (v.isError) return v;
|
|
1813
2101
|
const bv = v.coerceToBool();
|
|
1814
2102
|
if (bv.isError) return bv;
|
|
@@ -2068,14 +2356,18 @@ function datedif(a, c) {
|
|
|
2068
2356
|
function registerLookup(r) {
|
|
2069
2357
|
r.register("VLOOKUP", vlookup, 3, 4);
|
|
2070
2358
|
r.register("HLOOKUP", hlookup, 3, 4);
|
|
2359
|
+
r.register("XLOOKUP", xlookup, 3, 6);
|
|
2360
|
+
r.register("LOOKUP", lookup, 2, 3);
|
|
2071
2361
|
r.register("INDEX", index_, 2, 3);
|
|
2072
2362
|
r.register("MATCH", match, 2, 3);
|
|
2073
2363
|
r.register("CHOOSE", choose, 2);
|
|
2364
|
+
r.register("ADDRESS", address, 2, 5);
|
|
2074
2365
|
r.register("ROW", row, 0, 1);
|
|
2075
2366
|
r.register("COLUMN", column, 0, 1);
|
|
2076
2367
|
r.register("ROWS", rows, 1, 1);
|
|
2077
2368
|
r.register("COLUMNS", columns, 1, 1);
|
|
2078
2369
|
r.register("OFFSET", offset, 3, 5, true);
|
|
2370
|
+
r.register("INDIRECT", indirect, 1, 2, true);
|
|
2079
2371
|
}
|
|
2080
2372
|
function num2(a, c, i) {
|
|
2081
2373
|
const r = FormulaHelper.evalDouble(a[i], c);
|
|
@@ -2141,6 +2433,104 @@ function hlookup(a, c) {
|
|
|
2141
2433
|
}
|
|
2142
2434
|
return best >= 0 ? tbl.get(rowIdx, best) : FormulaValue.errorNA;
|
|
2143
2435
|
}
|
|
2436
|
+
function wildcardRegex(pattern) {
|
|
2437
|
+
let out = "";
|
|
2438
|
+
for (let i = 0; i < pattern.length; i++) {
|
|
2439
|
+
const ch = pattern[i];
|
|
2440
|
+
if (ch === "~" && i + 1 < pattern.length) {
|
|
2441
|
+
const next = pattern[++i];
|
|
2442
|
+
out += next.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2443
|
+
} else if (ch === "*") out += ".*";
|
|
2444
|
+
else if (ch === "?") out += ".";
|
|
2445
|
+
else out += ch.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2446
|
+
}
|
|
2447
|
+
return new RegExp(`^${out}$`, "i");
|
|
2448
|
+
}
|
|
2449
|
+
function findMatch(n, get, lookupVal, matchMode, searchMode) {
|
|
2450
|
+
if ((searchMode === 2 || searchMode === -2) && matchMode !== 2) {
|
|
2451
|
+
const at = searchMode === 2 ? get : (j) => get(n - 1 - j);
|
|
2452
|
+
let lo = 0, hi = n - 1, lastLE = -1, firstGE = -1;
|
|
2453
|
+
while (lo <= hi) {
|
|
2454
|
+
const mid2 = lo + hi >>> 1;
|
|
2455
|
+
const cmp = FormulaValue.compare(at(mid2), lookupVal);
|
|
2456
|
+
if (cmp === 0) return searchMode === 2 ? mid2 : n - 1 - mid2;
|
|
2457
|
+
if (cmp < 0) {
|
|
2458
|
+
lastLE = mid2;
|
|
2459
|
+
lo = mid2 + 1;
|
|
2460
|
+
} else {
|
|
2461
|
+
firstGE = mid2;
|
|
2462
|
+
hi = mid2 - 1;
|
|
2463
|
+
}
|
|
2464
|
+
}
|
|
2465
|
+
const idx = matchMode === -1 ? lastLE : matchMode === 1 ? firstGE : -1;
|
|
2466
|
+
return idx < 0 ? -1 : searchMode === 2 ? idx : n - 1 - idx;
|
|
2467
|
+
}
|
|
2468
|
+
const reverse = searchMode === -1;
|
|
2469
|
+
const order = reverse ? Array.from({ length: n }, (_, k) => n - 1 - k) : Array.from({ length: n }, (_, k) => k);
|
|
2470
|
+
if (matchMode === 2) {
|
|
2471
|
+
const re = wildcardRegex(lookupVal.asText());
|
|
2472
|
+
for (const i of order) if (re.test(get(i).asText())) return i;
|
|
2473
|
+
return -1;
|
|
2474
|
+
}
|
|
2475
|
+
if (matchMode === 0) {
|
|
2476
|
+
for (const i of order) if (FormulaValue.areEqual(get(i), lookupVal)) return i;
|
|
2477
|
+
return -1;
|
|
2478
|
+
}
|
|
2479
|
+
let best = -1;
|
|
2480
|
+
let bestVal = null;
|
|
2481
|
+
for (const i of order) {
|
|
2482
|
+
const v = get(i);
|
|
2483
|
+
const cmp = FormulaValue.compare(v, lookupVal);
|
|
2484
|
+
if (cmp === 0) return i;
|
|
2485
|
+
if (matchMode === -1 && cmp < 0) {
|
|
2486
|
+
if (bestVal === null || FormulaValue.compare(v, bestVal) > 0) {
|
|
2487
|
+
best = i;
|
|
2488
|
+
bestVal = v;
|
|
2489
|
+
}
|
|
2490
|
+
} else if (matchMode === 1 && cmp > 0) {
|
|
2491
|
+
if (bestVal === null || FormulaValue.compare(v, bestVal) < 0) {
|
|
2492
|
+
best = i;
|
|
2493
|
+
bestVal = v;
|
|
2494
|
+
}
|
|
2495
|
+
}
|
|
2496
|
+
}
|
|
2497
|
+
return best;
|
|
2498
|
+
}
|
|
2499
|
+
function xlookup(a, c) {
|
|
2500
|
+
const lookupVal = a[0].evaluate(c);
|
|
2501
|
+
if (lookupVal.isError) return lookupVal;
|
|
2502
|
+
const lookupRaw = a[1].evaluate(c);
|
|
2503
|
+
if (lookupRaw.isError) return lookupRaw;
|
|
2504
|
+
const returnRaw = a[2].evaluate(c);
|
|
2505
|
+
if (returnRaw.isError) return returnRaw;
|
|
2506
|
+
const matchMode = a.length > 4 ? num2(a, c, 4) : { ok: true, n: 0 };
|
|
2507
|
+
if (!matchMode.ok) return matchMode.e;
|
|
2508
|
+
const searchMode = a.length > 5 ? num2(a, c, 5) : { ok: true, n: 1 };
|
|
2509
|
+
if (!searchMode.ok) return searchMode.e;
|
|
2510
|
+
const mm = Math.trunc(matchMode.n), sm = Math.trunc(searchMode.n);
|
|
2511
|
+
const la = lookupRaw.isArray ? lookupRaw.arrayVal : ArrayValue.fromScalar(lookupRaw);
|
|
2512
|
+
if (la.rows > 1 && la.columns > 1) return FormulaValue.errorValue;
|
|
2513
|
+
const vertical = !(la.rows === 1 && la.columns > 1);
|
|
2514
|
+
const n = vertical ? la.rows : la.columns;
|
|
2515
|
+
const get = vertical ? (i) => la.get(i, 0) : (i) => la.get(0, i);
|
|
2516
|
+
const idx = findMatch(n, get, lookupVal, mm, sm);
|
|
2517
|
+
if (idx < 0) {
|
|
2518
|
+
return a.length > 3 ? a[3].evaluate(c) : FormulaValue.errorNA;
|
|
2519
|
+
}
|
|
2520
|
+
const ret = returnRaw.isArray ? returnRaw.arrayVal : ArrayValue.fromScalar(returnRaw);
|
|
2521
|
+
if (vertical) {
|
|
2522
|
+
if (ret.rows !== n) return FormulaValue.errorValue;
|
|
2523
|
+
if (ret.columns === 1) return ret.get(idx, 0);
|
|
2524
|
+
const out2 = new ArrayValue(1, ret.columns);
|
|
2525
|
+
for (let col = 0; col < ret.columns; col++) out2.set(0, col, ret.get(idx, col));
|
|
2526
|
+
return FormulaValue.array(out2);
|
|
2527
|
+
}
|
|
2528
|
+
if (ret.columns !== n) return FormulaValue.errorValue;
|
|
2529
|
+
if (ret.rows === 1) return ret.get(0, idx);
|
|
2530
|
+
const out = new ArrayValue(ret.rows, 1);
|
|
2531
|
+
for (let r = 0; r < ret.rows; r++) out.set(r, 0, ret.get(r, idx));
|
|
2532
|
+
return FormulaValue.array(out);
|
|
2533
|
+
}
|
|
2144
2534
|
function index_(a, c) {
|
|
2145
2535
|
const arrVal = a[0].evaluate(c);
|
|
2146
2536
|
if (arrVal.isError) return arrVal;
|
|
@@ -2204,6 +2594,86 @@ function choose(a, c) {
|
|
|
2204
2594
|
if (idx < 1 || idx >= a.length) return FormulaValue.errorValue;
|
|
2205
2595
|
return a[idx].evaluate(c);
|
|
2206
2596
|
}
|
|
2597
|
+
function approxMatchFlat(arr, lookupVal) {
|
|
2598
|
+
let best = -1;
|
|
2599
|
+
for (let i = 0; i < arr.length; i++) {
|
|
2600
|
+
if (FormulaValue.compare(arr.getFlat(i), lookupVal) <= 0) best = i;
|
|
2601
|
+
else break;
|
|
2602
|
+
}
|
|
2603
|
+
return best;
|
|
2604
|
+
}
|
|
2605
|
+
function lookup(a, c) {
|
|
2606
|
+
const lookupVal = a[0].evaluate(c);
|
|
2607
|
+
if (lookupVal.isError) return lookupVal;
|
|
2608
|
+
const vecVal = a[1].evaluate(c);
|
|
2609
|
+
if (vecVal.isError) return vecVal;
|
|
2610
|
+
if (a.length > 2) {
|
|
2611
|
+
const resVal = a[2].evaluate(c);
|
|
2612
|
+
if (resVal.isError) return resVal;
|
|
2613
|
+
const vecArr = vecVal.isArray ? vecVal.arrayVal : ArrayValue.fromScalar(vecVal);
|
|
2614
|
+
const idx = approxMatchFlat(vecArr, lookupVal);
|
|
2615
|
+
if (idx < 0) return FormulaValue.errorNA;
|
|
2616
|
+
if (resVal.isArray) return resVal.arrayVal.getFlat(idx);
|
|
2617
|
+
return idx === 0 ? resVal : FormulaValue.errorNA;
|
|
2618
|
+
}
|
|
2619
|
+
if (!vecVal.isArray) {
|
|
2620
|
+
return FormulaValue.areEqual(vecVal, lookupVal) ? vecVal : FormulaValue.errorNA;
|
|
2621
|
+
}
|
|
2622
|
+
const arr = vecVal.arrayVal;
|
|
2623
|
+
if (arr.columns >= arr.rows) {
|
|
2624
|
+
let best2 = -1;
|
|
2625
|
+
for (let col = 0; col < arr.columns; col++) {
|
|
2626
|
+
if (FormulaValue.compare(arr.get(0, col), lookupVal) <= 0) best2 = col;
|
|
2627
|
+
else break;
|
|
2628
|
+
}
|
|
2629
|
+
return best2 >= 0 ? arr.get(arr.rows - 1, best2) : FormulaValue.errorNA;
|
|
2630
|
+
}
|
|
2631
|
+
let best = -1;
|
|
2632
|
+
for (let r = 0; r < arr.rows; r++) {
|
|
2633
|
+
if (FormulaValue.compare(arr.get(r, 0), lookupVal) <= 0) best = r;
|
|
2634
|
+
else break;
|
|
2635
|
+
}
|
|
2636
|
+
return best >= 0 ? arr.get(best, arr.columns - 1) : FormulaValue.errorNA;
|
|
2637
|
+
}
|
|
2638
|
+
function address(a, c) {
|
|
2639
|
+
const rn = num2(a, c, 0);
|
|
2640
|
+
if (!rn.ok) return rn.e;
|
|
2641
|
+
const cn = num2(a, c, 1);
|
|
2642
|
+
if (!cn.ok) return cn.e;
|
|
2643
|
+
const row2 = Math.round(rn.n);
|
|
2644
|
+
const col = Math.round(cn.n);
|
|
2645
|
+
if (row2 < 1 || col < 1) return FormulaValue.errorValue;
|
|
2646
|
+
let absNum = 1;
|
|
2647
|
+
if (a.length > 2) {
|
|
2648
|
+
const r = num2(a, c, 2);
|
|
2649
|
+
if (!r.ok) return r.e;
|
|
2650
|
+
absNum = Math.round(r.n);
|
|
2651
|
+
}
|
|
2652
|
+
if (absNum < 1 || absNum > 4) return FormulaValue.errorValue;
|
|
2653
|
+
let a1 = true;
|
|
2654
|
+
if (a.length > 3) {
|
|
2655
|
+
const v = a[3].evaluate(c);
|
|
2656
|
+
if (v.isError) return v;
|
|
2657
|
+
a1 = v.isBlank ? true : v.coerceToBool().booleanValue;
|
|
2658
|
+
}
|
|
2659
|
+
let sheetPrefix = "";
|
|
2660
|
+
if (a.length > 4) {
|
|
2661
|
+
const s = FormulaHelper.evalString(a[4], c);
|
|
2662
|
+
if (!s.ok) return s.error;
|
|
2663
|
+
if (s.value !== "") sheetPrefix = `${s.value}!`;
|
|
2664
|
+
}
|
|
2665
|
+
const rowAbs = absNum === 1 || absNum === 2;
|
|
2666
|
+
const colAbs = absNum === 1 || absNum === 3;
|
|
2667
|
+
let ref;
|
|
2668
|
+
if (a1) {
|
|
2669
|
+
ref = `${colAbs ? "$" : ""}${columnLetter(col)}${rowAbs ? "$" : ""}${row2}`;
|
|
2670
|
+
} else {
|
|
2671
|
+
const rPart = rowAbs ? `R${row2}` : `R[${row2}]`;
|
|
2672
|
+
const cPart = colAbs ? `C${col}` : `C[${col}]`;
|
|
2673
|
+
ref = `${rPart}${cPart}`;
|
|
2674
|
+
}
|
|
2675
|
+
return FormulaValue.text(`${sheetPrefix}${ref}`);
|
|
2676
|
+
}
|
|
2207
2677
|
function row(a, c) {
|
|
2208
2678
|
if (a.length === 0) return FormulaValue.number(c.formulaRow || 1);
|
|
2209
2679
|
const node = a[0];
|
|
@@ -2242,6 +2712,61 @@ function columns(a, c) {
|
|
|
2242
2712
|
const v = a[0].evaluate(c);
|
|
2243
2713
|
return v.isArray ? FormulaValue.number(v.arrayVal.columns) : FormulaValue.one;
|
|
2244
2714
|
}
|
|
2715
|
+
function indirect(a, c) {
|
|
2716
|
+
const s = FormulaHelper.evalString(a[0], c);
|
|
2717
|
+
if (!s.ok) return s.error;
|
|
2718
|
+
let a1 = true;
|
|
2719
|
+
if (a.length > 1) {
|
|
2720
|
+
const v = a[1].evaluate(c);
|
|
2721
|
+
if (v.isError) return v;
|
|
2722
|
+
a1 = v.isBlank ? true : v.coerceToBool().booleanValue;
|
|
2723
|
+
}
|
|
2724
|
+
const text = s.value.trim();
|
|
2725
|
+
if (text === "") return FormulaValue.errorRef;
|
|
2726
|
+
let sheet;
|
|
2727
|
+
let body = text;
|
|
2728
|
+
const bang = text.lastIndexOf("!");
|
|
2729
|
+
if (bang >= 0) {
|
|
2730
|
+
sheet = text.slice(0, bang).replace(/^'|'$/g, "");
|
|
2731
|
+
body = text.slice(bang + 1);
|
|
2732
|
+
}
|
|
2733
|
+
const colon = body.indexOf(":");
|
|
2734
|
+
try {
|
|
2735
|
+
if (colon >= 0) {
|
|
2736
|
+
const start = toA1(body.slice(0, colon), a1, c);
|
|
2737
|
+
const end = toA1(body.slice(colon + 1), a1, c);
|
|
2738
|
+
if (start === null || end === null) return FormulaValue.errorRef;
|
|
2739
|
+
return sheet !== void 0 ? c.getSheetRangeValues(sheet, start, end) : c.getRangeValues(start, end);
|
|
2740
|
+
}
|
|
2741
|
+
const cell = toA1(body, a1, c);
|
|
2742
|
+
if (cell === null) return FormulaValue.errorRef;
|
|
2743
|
+
return sheet !== void 0 ? c.getSheetCellValue(sheet, cell) : c.getCellValue(cell);
|
|
2744
|
+
} catch {
|
|
2745
|
+
return FormulaValue.errorRef;
|
|
2746
|
+
}
|
|
2747
|
+
}
|
|
2748
|
+
function toA1(ref, a1, c) {
|
|
2749
|
+
const r = ref.trim();
|
|
2750
|
+
if (a1) {
|
|
2751
|
+
try {
|
|
2752
|
+
const { row: row3, column: column2 } = parseCellRef(r);
|
|
2753
|
+
return cellRefFromRowCol(row3, column2);
|
|
2754
|
+
} catch {
|
|
2755
|
+
return null;
|
|
2756
|
+
}
|
|
2757
|
+
}
|
|
2758
|
+
const m = /^R(\[-?\d+\]|\d+)?C(\[-?\d+\]|\d+)?$/i.exec(r);
|
|
2759
|
+
if (!m) return null;
|
|
2760
|
+
const axis = (part, base) => {
|
|
2761
|
+
if (part === void 0) return base;
|
|
2762
|
+
if (part.startsWith("[")) return base + parseInt(part.slice(1, -1), 10);
|
|
2763
|
+
return parseInt(part, 10);
|
|
2764
|
+
};
|
|
2765
|
+
const row2 = axis(m[1], c.formulaRow || 1);
|
|
2766
|
+
const col = axis(m[2], c.formulaCol || 1);
|
|
2767
|
+
if (row2 === null || col === null || row2 < 1 || col < 1) return null;
|
|
2768
|
+
return cellRefFromRowCol(row2, col);
|
|
2769
|
+
}
|
|
2245
2770
|
function offset(a, c) {
|
|
2246
2771
|
const baseNode = a[0];
|
|
2247
2772
|
let baseRef;
|
|
@@ -2298,8 +2823,8 @@ function registerStatistical(r) {
|
|
|
2298
2823
|
}
|
|
2299
2824
|
function variance(nums, population) {
|
|
2300
2825
|
const mean = nums.reduce((s, n) => s + n, 0) / nums.length;
|
|
2301
|
-
const
|
|
2302
|
-
return
|
|
2826
|
+
const sumSq2 = nums.reduce((s, n) => s + (n - mean) ** 2, 0);
|
|
2827
|
+
return sumSq2 / (population ? nums.length : nums.length - 1);
|
|
2303
2828
|
}
|
|
2304
2829
|
function numsFromArray(v) {
|
|
2305
2830
|
if (v.isArray) {
|
|
@@ -2532,6 +3057,834 @@ function errorType(a, c) {
|
|
|
2532
3057
|
return FormulaValue.number(map[v.errorCode] ?? 7);
|
|
2533
3058
|
}
|
|
2534
3059
|
|
|
3060
|
+
// src/functions/finance-functions.ts
|
|
3061
|
+
function registerFinance(r) {
|
|
3062
|
+
r.register("PMT", pmt, 3, 5);
|
|
3063
|
+
r.register("FV", fv, 3, 5);
|
|
3064
|
+
r.register("PV", pv, 3, 5);
|
|
3065
|
+
r.register("NPV", npv, 2);
|
|
3066
|
+
r.register("IRR", irr, 1, 2);
|
|
3067
|
+
r.register("RATE", rate, 3, 6);
|
|
3068
|
+
r.register("NPER", nper, 3, 5);
|
|
3069
|
+
r.register("XNPV", xnpv, 3, 3);
|
|
3070
|
+
r.register("XIRR", xirr, 2, 3);
|
|
3071
|
+
}
|
|
3072
|
+
function arg(a, c, idx, dflt) {
|
|
3073
|
+
if (idx >= a.length) return { ok: true, n: dflt };
|
|
3074
|
+
const r = FormulaHelper.evalDouble(a[idx], c);
|
|
3075
|
+
return r.ok ? { ok: true, n: r.value } : { ok: false, e: r.error };
|
|
3076
|
+
}
|
|
3077
|
+
function pmt(a, c) {
|
|
3078
|
+
const rate2 = arg(a, c, 0, 0);
|
|
3079
|
+
if (!rate2.ok) return rate2.e;
|
|
3080
|
+
const nper2 = arg(a, c, 1, 0);
|
|
3081
|
+
if (!nper2.ok) return nper2.e;
|
|
3082
|
+
const pvv = arg(a, c, 2, 0);
|
|
3083
|
+
if (!pvv.ok) return pvv.e;
|
|
3084
|
+
const fvv = arg(a, c, 3, 0);
|
|
3085
|
+
if (!fvv.ok) return fvv.e;
|
|
3086
|
+
const type = arg(a, c, 4, 0);
|
|
3087
|
+
if (!type.ok) return type.e;
|
|
3088
|
+
const r = rate2.n, n = nper2.n, present = pvv.n, future = fvv.n, t = type.n;
|
|
3089
|
+
if (n === 0) return FormulaValue.errorNum;
|
|
3090
|
+
if (r === 0) return FormulaValue.number(-(present + future) / n);
|
|
3091
|
+
const pow = Math.pow(1 + r, n);
|
|
3092
|
+
let payment = (-future - present * pow) * r / (pow - 1);
|
|
3093
|
+
if (t === 1) payment /= 1 + r;
|
|
3094
|
+
return FormulaValue.number(payment);
|
|
3095
|
+
}
|
|
3096
|
+
function fv(a, c) {
|
|
3097
|
+
const rate2 = arg(a, c, 0, 0);
|
|
3098
|
+
if (!rate2.ok) return rate2.e;
|
|
3099
|
+
const nper2 = arg(a, c, 1, 0);
|
|
3100
|
+
if (!nper2.ok) return nper2.e;
|
|
3101
|
+
const pmtv = arg(a, c, 2, 0);
|
|
3102
|
+
if (!pmtv.ok) return pmtv.e;
|
|
3103
|
+
const pvv = arg(a, c, 3, 0);
|
|
3104
|
+
if (!pvv.ok) return pvv.e;
|
|
3105
|
+
const type = arg(a, c, 4, 0);
|
|
3106
|
+
if (!type.ok) return type.e;
|
|
3107
|
+
const r = rate2.n, n = nper2.n, payment = pmtv.n, present = pvv.n, t = type.n;
|
|
3108
|
+
if (r === 0) return FormulaValue.number(-(present + payment * n));
|
|
3109
|
+
const pow = Math.pow(1 + r, n);
|
|
3110
|
+
return FormulaValue.number(-(present * pow + payment * (1 + r * t) * (pow - 1) / r));
|
|
3111
|
+
}
|
|
3112
|
+
function pv(a, c) {
|
|
3113
|
+
const rate2 = arg(a, c, 0, 0);
|
|
3114
|
+
if (!rate2.ok) return rate2.e;
|
|
3115
|
+
const nper2 = arg(a, c, 1, 0);
|
|
3116
|
+
if (!nper2.ok) return nper2.e;
|
|
3117
|
+
const pmtv = arg(a, c, 2, 0);
|
|
3118
|
+
if (!pmtv.ok) return pmtv.e;
|
|
3119
|
+
const fvv = arg(a, c, 3, 0);
|
|
3120
|
+
if (!fvv.ok) return fvv.e;
|
|
3121
|
+
const type = arg(a, c, 4, 0);
|
|
3122
|
+
if (!type.ok) return type.e;
|
|
3123
|
+
const r = rate2.n, n = nper2.n, payment = pmtv.n, future = fvv.n, t = type.n;
|
|
3124
|
+
if (r === 0) return FormulaValue.number(-(future + payment * n));
|
|
3125
|
+
const pow = Math.pow(1 + r, n);
|
|
3126
|
+
return FormulaValue.number(-(future + payment * (1 + r * t) * (pow - 1) / r) / pow);
|
|
3127
|
+
}
|
|
3128
|
+
function npv(a, c) {
|
|
3129
|
+
const rate2 = FormulaHelper.evalDouble(a[0], c);
|
|
3130
|
+
if (!rate2.ok) return rate2.error;
|
|
3131
|
+
if (rate2.value === -1) return FormulaValue.errorDiv0;
|
|
3132
|
+
const flows = FormulaHelper.collectNumbers(a.slice(1), c);
|
|
3133
|
+
if (!flows.ok) return flows.error;
|
|
3134
|
+
let total = 0;
|
|
3135
|
+
for (let i = 0; i < flows.values.length; i++) {
|
|
3136
|
+
total += flows.values[i] / Math.pow(1 + rate2.value, i + 1);
|
|
3137
|
+
}
|
|
3138
|
+
return FormulaValue.number(total);
|
|
3139
|
+
}
|
|
3140
|
+
function irr(a, c) {
|
|
3141
|
+
const flowsRes = FormulaHelper.collectNumbers([a[0]], c);
|
|
3142
|
+
if (!flowsRes.ok) return flowsRes.error;
|
|
3143
|
+
const flows = flowsRes.values;
|
|
3144
|
+
if (flows.length < 2) return FormulaValue.errorNum;
|
|
3145
|
+
let guess = 0.1;
|
|
3146
|
+
if (a.length > 1) {
|
|
3147
|
+
const g = FormulaHelper.evalDouble(a[1], c);
|
|
3148
|
+
if (!g.ok) return g.error;
|
|
3149
|
+
guess = g.value;
|
|
3150
|
+
}
|
|
3151
|
+
const npvAt = (rate3) => {
|
|
3152
|
+
let sum2 = 0;
|
|
3153
|
+
for (let i = 0; i < flows.length; i++) sum2 += flows[i] / Math.pow(1 + rate3, i);
|
|
3154
|
+
return sum2;
|
|
3155
|
+
};
|
|
3156
|
+
let rate2 = guess;
|
|
3157
|
+
for (let iter = 0; iter < 100; iter++) {
|
|
3158
|
+
const f = npvAt(rate2);
|
|
3159
|
+
if (Math.abs(f) < 1e-7) return FormulaValue.number(rate2);
|
|
3160
|
+
const h = 1e-6;
|
|
3161
|
+
const deriv = (npvAt(rate2 + h) - f) / h;
|
|
3162
|
+
if (deriv === 0) break;
|
|
3163
|
+
const next = rate2 - f / deriv;
|
|
3164
|
+
if (!isFinite(next) || next <= -1) break;
|
|
3165
|
+
if (Math.abs(next - rate2) < 1e-9) {
|
|
3166
|
+
rate2 = next;
|
|
3167
|
+
break;
|
|
3168
|
+
}
|
|
3169
|
+
rate2 = next;
|
|
3170
|
+
}
|
|
3171
|
+
if (Math.abs(npvAt(rate2)) < 1e-6) return FormulaValue.number(rate2);
|
|
3172
|
+
return FormulaValue.errorNum;
|
|
3173
|
+
}
|
|
3174
|
+
function tvm(r, n, pmt2, pv2, fv2, type) {
|
|
3175
|
+
if (r === 0) return pv2 + pmt2 * n + fv2;
|
|
3176
|
+
const pow = Math.pow(1 + r, n);
|
|
3177
|
+
return pv2 * pow + pmt2 * (1 + r * type) * (pow - 1) / r + fv2;
|
|
3178
|
+
}
|
|
3179
|
+
function rate(a, c) {
|
|
3180
|
+
const nper2 = arg(a, c, 0, 0);
|
|
3181
|
+
if (!nper2.ok) return nper2.e;
|
|
3182
|
+
const pmtv = arg(a, c, 1, 0);
|
|
3183
|
+
if (!pmtv.ok) return pmtv.e;
|
|
3184
|
+
const pvv = arg(a, c, 2, 0);
|
|
3185
|
+
if (!pvv.ok) return pvv.e;
|
|
3186
|
+
const fvv = arg(a, c, 3, 0);
|
|
3187
|
+
if (!fvv.ok) return fvv.e;
|
|
3188
|
+
const type = arg(a, c, 4, 0);
|
|
3189
|
+
if (!type.ok) return type.e;
|
|
3190
|
+
const gs = arg(a, c, 5, 0.1);
|
|
3191
|
+
if (!gs.ok) return gs.e;
|
|
3192
|
+
const n = nper2.n, pmt2 = pmtv.n, pv2 = pvv.n, fv2 = fvv.n, t = type.n;
|
|
3193
|
+
if (n === 0) return FormulaValue.errorNum;
|
|
3194
|
+
let r = gs.n;
|
|
3195
|
+
for (let iter = 0; iter < 100; iter++) {
|
|
3196
|
+
const f = tvm(r, n, pmt2, pv2, fv2, t);
|
|
3197
|
+
if (Math.abs(f) < 1e-8) return FormulaValue.number(r);
|
|
3198
|
+
const h = 1e-6;
|
|
3199
|
+
const deriv = (tvm(r + h, n, pmt2, pv2, fv2, t) - f) / h;
|
|
3200
|
+
if (deriv === 0) break;
|
|
3201
|
+
const next = r - f / deriv;
|
|
3202
|
+
if (!isFinite(next) || next <= -1) break;
|
|
3203
|
+
if (Math.abs(next - r) < 1e-10) {
|
|
3204
|
+
r = next;
|
|
3205
|
+
break;
|
|
3206
|
+
}
|
|
3207
|
+
r = next;
|
|
3208
|
+
}
|
|
3209
|
+
if (Math.abs(tvm(r, n, pmt2, pv2, fv2, t)) < 1e-6) return FormulaValue.number(r);
|
|
3210
|
+
return FormulaValue.errorNum;
|
|
3211
|
+
}
|
|
3212
|
+
function nper(a, c) {
|
|
3213
|
+
const rate2 = arg(a, c, 0, 0);
|
|
3214
|
+
if (!rate2.ok) return rate2.e;
|
|
3215
|
+
const pmtv = arg(a, c, 1, 0);
|
|
3216
|
+
if (!pmtv.ok) return pmtv.e;
|
|
3217
|
+
const pvv = arg(a, c, 2, 0);
|
|
3218
|
+
if (!pvv.ok) return pvv.e;
|
|
3219
|
+
const fvv = arg(a, c, 3, 0);
|
|
3220
|
+
if (!fvv.ok) return fvv.e;
|
|
3221
|
+
const type = arg(a, c, 4, 0);
|
|
3222
|
+
if (!type.ok) return type.e;
|
|
3223
|
+
const r = rate2.n, pmt2 = pmtv.n, pv2 = pvv.n, fv2 = fvv.n, t = type.n;
|
|
3224
|
+
if (r === 0) {
|
|
3225
|
+
if (pmt2 === 0) return FormulaValue.errorNum;
|
|
3226
|
+
return FormulaValue.number(-(pv2 + fv2) / pmt2);
|
|
3227
|
+
}
|
|
3228
|
+
const adj = pmt2 * (1 + r * t);
|
|
3229
|
+
const num5 = adj - fv2 * r;
|
|
3230
|
+
const den = adj + pv2 * r;
|
|
3231
|
+
if (den === 0 || num5 / den <= 0) return FormulaValue.errorNum;
|
|
3232
|
+
const result = Math.log(num5 / den) / Math.log(1 + r);
|
|
3233
|
+
if (!isFinite(result)) return FormulaValue.errorNum;
|
|
3234
|
+
return FormulaValue.number(result);
|
|
3235
|
+
}
|
|
3236
|
+
function flatNumbers(node, c) {
|
|
3237
|
+
const v = node.evaluate(c);
|
|
3238
|
+
if (v.isError) return { ok: false, e: v };
|
|
3239
|
+
const out = [];
|
|
3240
|
+
const push = (item) => {
|
|
3241
|
+
if (item.isError) return item;
|
|
3242
|
+
const d = item.tryAsDouble();
|
|
3243
|
+
if (!d.ok) return FormulaValue.errorValue;
|
|
3244
|
+
out.push(d.value);
|
|
3245
|
+
return null;
|
|
3246
|
+
};
|
|
3247
|
+
if (v.isArray) {
|
|
3248
|
+
for (const item of v.arrayVal.values()) {
|
|
3249
|
+
const err = push(item);
|
|
3250
|
+
if (err) return { ok: false, e: err };
|
|
3251
|
+
}
|
|
3252
|
+
} else {
|
|
3253
|
+
const err = push(v);
|
|
3254
|
+
if (err) return { ok: false, e: err };
|
|
3255
|
+
}
|
|
3256
|
+
return { ok: true, values: out };
|
|
3257
|
+
}
|
|
3258
|
+
function xnpvAt(rate2, values, days2) {
|
|
3259
|
+
let sum2 = 0;
|
|
3260
|
+
for (let i = 0; i < values.length; i++) {
|
|
3261
|
+
sum2 += values[i] / Math.pow(1 + rate2, days2[i] / 365);
|
|
3262
|
+
}
|
|
3263
|
+
return sum2;
|
|
3264
|
+
}
|
|
3265
|
+
function xnpv(a, c) {
|
|
3266
|
+
const rateRes = FormulaHelper.evalDouble(a[0], c);
|
|
3267
|
+
if (!rateRes.ok) return rateRes.error;
|
|
3268
|
+
const rate2 = rateRes.value;
|
|
3269
|
+
if (rate2 <= -1) return FormulaValue.errorNum;
|
|
3270
|
+
const valsRes = flatNumbers(a[1], c);
|
|
3271
|
+
if (!valsRes.ok) return valsRes.e;
|
|
3272
|
+
const datesRes = flatNumbers(a[2], c);
|
|
3273
|
+
if (!datesRes.ok) return datesRes.e;
|
|
3274
|
+
const values = valsRes.values;
|
|
3275
|
+
const dates = datesRes.values;
|
|
3276
|
+
if (values.length === 0 || values.length !== dates.length) return FormulaValue.errorNum;
|
|
3277
|
+
const base = Math.trunc(dates[0]);
|
|
3278
|
+
const days2 = dates.map((d) => Math.trunc(d) - base);
|
|
3279
|
+
if (days2.some((d) => d < 0)) return FormulaValue.errorNum;
|
|
3280
|
+
return FormulaValue.number(xnpvAt(rate2, values, days2));
|
|
3281
|
+
}
|
|
3282
|
+
function xirr(a, c) {
|
|
3283
|
+
const valsRes = flatNumbers(a[0], c);
|
|
3284
|
+
if (!valsRes.ok) return valsRes.e;
|
|
3285
|
+
const datesRes = flatNumbers(a[1], c);
|
|
3286
|
+
if (!datesRes.ok) return datesRes.e;
|
|
3287
|
+
const values = valsRes.values;
|
|
3288
|
+
const dates = datesRes.values;
|
|
3289
|
+
if (values.length < 2 || values.length !== dates.length) return FormulaValue.errorNum;
|
|
3290
|
+
let guess = 0.1;
|
|
3291
|
+
if (a.length > 2) {
|
|
3292
|
+
const g = FormulaHelper.evalDouble(a[2], c);
|
|
3293
|
+
if (!g.ok) return g.error;
|
|
3294
|
+
guess = g.value;
|
|
3295
|
+
}
|
|
3296
|
+
const base = Math.trunc(dates[0]);
|
|
3297
|
+
const days2 = dates.map((d) => Math.trunc(d) - base);
|
|
3298
|
+
if (days2.some((d) => d < 0)) return FormulaValue.errorNum;
|
|
3299
|
+
const derivAt = (rate3) => {
|
|
3300
|
+
let sum2 = 0;
|
|
3301
|
+
for (let i = 0; i < values.length; i++) {
|
|
3302
|
+
const e = days2[i] / 365;
|
|
3303
|
+
sum2 += -e * values[i] / Math.pow(1 + rate3, e + 1);
|
|
3304
|
+
}
|
|
3305
|
+
return sum2;
|
|
3306
|
+
};
|
|
3307
|
+
let rate2 = guess;
|
|
3308
|
+
for (let iter = 0; iter < 100; iter++) {
|
|
3309
|
+
const f = xnpvAt(rate2, values, days2);
|
|
3310
|
+
if (Math.abs(f) < 1e-7) return FormulaValue.number(rate2);
|
|
3311
|
+
const deriv = derivAt(rate2);
|
|
3312
|
+
if (deriv === 0) break;
|
|
3313
|
+
const next = rate2 - f / deriv;
|
|
3314
|
+
if (!isFinite(next) || next <= -1) break;
|
|
3315
|
+
if (Math.abs(next - rate2) < 1e-9) {
|
|
3316
|
+
rate2 = next;
|
|
3317
|
+
break;
|
|
3318
|
+
}
|
|
3319
|
+
rate2 = next;
|
|
3320
|
+
}
|
|
3321
|
+
if (Math.abs(xnpvAt(rate2, values, days2)) < 1e-6) return FormulaValue.number(rate2);
|
|
3322
|
+
return FormulaValue.errorNum;
|
|
3323
|
+
}
|
|
3324
|
+
|
|
3325
|
+
// src/functions/meta-functions.ts
|
|
3326
|
+
var MAX_TAIL_ITERATIONS = 1e7;
|
|
3327
|
+
function registerMeta(r) {
|
|
3328
|
+
r.register("LET", let_, 3);
|
|
3329
|
+
r.register("LAMBDA", lambda_, 1);
|
|
3330
|
+
r.register("MAP", map_, 2);
|
|
3331
|
+
r.register("REDUCE", reduce_, 3, 3);
|
|
3332
|
+
r.register("SCAN", scan_, 3, 3);
|
|
3333
|
+
r.register("BYROW", byRow, 2, 2);
|
|
3334
|
+
r.register("BYCOL", byCol, 2, 2);
|
|
3335
|
+
}
|
|
3336
|
+
var asArray = (v) => v.isArray ? v.arrayVal : ArrayValue.fromScalar(v);
|
|
3337
|
+
function let_(a, c) {
|
|
3338
|
+
if (a.length < 3 || a.length % 2 === 0) return FormulaValue.errorValue;
|
|
3339
|
+
const bindings = /* @__PURE__ */ new Map();
|
|
3340
|
+
c.pushScope(bindings);
|
|
3341
|
+
try {
|
|
3342
|
+
for (let i = 0; i < a.length - 1; i += 2) {
|
|
3343
|
+
const nameNode = a[i];
|
|
3344
|
+
if (!(nameNode instanceof NamedRangeNode)) return FormulaValue.errorValue;
|
|
3345
|
+
const value2 = a[i + 1].evaluate(c);
|
|
3346
|
+
if (value2.isError) return value2;
|
|
3347
|
+
bindings.set(nameNode.name.toUpperCase(), value2);
|
|
3348
|
+
}
|
|
3349
|
+
return a[a.length - 1].evaluate(c);
|
|
3350
|
+
} finally {
|
|
3351
|
+
c.popScope();
|
|
3352
|
+
}
|
|
3353
|
+
}
|
|
3354
|
+
function lambda_(a, c) {
|
|
3355
|
+
const paramNodes = a.slice(0, -1);
|
|
3356
|
+
const body = a[a.length - 1];
|
|
3357
|
+
const params = [];
|
|
3358
|
+
for (const p of paramNodes) {
|
|
3359
|
+
if (!(p instanceof NamedRangeNode)) return FormulaValue.errorValue;
|
|
3360
|
+
params.push(p.name.toUpperCase());
|
|
3361
|
+
}
|
|
3362
|
+
const ctx = c;
|
|
3363
|
+
const lambda = {
|
|
3364
|
+
arity: params.length,
|
|
3365
|
+
// One tail-aware evaluation of the body: binds params, then evaluates in
|
|
3366
|
+
// tail mode so a self/other tail call surfaces as a TailCall.
|
|
3367
|
+
step(args) {
|
|
3368
|
+
const bindings = /* @__PURE__ */ new Map();
|
|
3369
|
+
params.forEach((p, i) => bindings.set(p, args[i] ?? FormulaValue.blank));
|
|
3370
|
+
ctx.pushScope(bindings);
|
|
3371
|
+
try {
|
|
3372
|
+
return body.evaluateTail(ctx);
|
|
3373
|
+
} finally {
|
|
3374
|
+
ctx.popScope();
|
|
3375
|
+
}
|
|
3376
|
+
},
|
|
3377
|
+
// Run to completion. Tail calls iterate here (O(1) stack); only non-tail
|
|
3378
|
+
// recursion re-enters call() and is bounded by the recursion guard.
|
|
3379
|
+
call(args) {
|
|
3380
|
+
const guard = ctx.recursionGuard;
|
|
3381
|
+
if (guard) {
|
|
3382
|
+
if (guard.depth >= guard.max) return FormulaValue.errorNum;
|
|
3383
|
+
guard.depth++;
|
|
3384
|
+
}
|
|
3385
|
+
try {
|
|
3386
|
+
let current = lambda;
|
|
3387
|
+
let currentArgs = args;
|
|
3388
|
+
for (let iter = 0; ; iter++) {
|
|
3389
|
+
if (iter > MAX_TAIL_ITERATIONS) return FormulaValue.errorNum;
|
|
3390
|
+
const r = current.step ? current.step(currentArgs) : current.call(currentArgs);
|
|
3391
|
+
if (r instanceof TailCall) {
|
|
3392
|
+
current = r.lambda;
|
|
3393
|
+
currentArgs = r.args;
|
|
3394
|
+
continue;
|
|
3395
|
+
}
|
|
3396
|
+
return r;
|
|
3397
|
+
}
|
|
3398
|
+
} finally {
|
|
3399
|
+
if (guard) guard.depth--;
|
|
3400
|
+
}
|
|
3401
|
+
}
|
|
3402
|
+
};
|
|
3403
|
+
return FormulaValue.lambda(lambda);
|
|
3404
|
+
}
|
|
3405
|
+
function lambdaArg(node, c) {
|
|
3406
|
+
const v = node.evaluate(c);
|
|
3407
|
+
if (v.isError) return { ok: false, e: v };
|
|
3408
|
+
if (!v.isLambda) return { ok: false, e: FormulaValue.errorValue };
|
|
3409
|
+
return { ok: true, fn: v.lambdaVal };
|
|
3410
|
+
}
|
|
3411
|
+
function map_(a, c) {
|
|
3412
|
+
const fn = lambdaArg(a[a.length - 1], c);
|
|
3413
|
+
if (!fn.ok) return fn.e;
|
|
3414
|
+
const arrays = a.slice(0, -1).map((n) => asArray(n.evaluate(c)));
|
|
3415
|
+
if (arrays.length === 0) return FormulaValue.errorValue;
|
|
3416
|
+
const rows2 = arrays[0].rows, cols = arrays[0].columns;
|
|
3417
|
+
const out = new ArrayValue(rows2, cols);
|
|
3418
|
+
for (let r = 0; r < rows2; r++) {
|
|
3419
|
+
for (let col = 0; col < cols; col++) {
|
|
3420
|
+
out.set(r, col, fn.fn.call(arrays.map((ar) => ar.get(r, col))));
|
|
3421
|
+
}
|
|
3422
|
+
}
|
|
3423
|
+
return FormulaValue.array(out);
|
|
3424
|
+
}
|
|
3425
|
+
function reduce_(a, c) {
|
|
3426
|
+
let acc = a[0].evaluate(c);
|
|
3427
|
+
if (acc.isError) return acc;
|
|
3428
|
+
const arr = asArray(a[1].evaluate(c));
|
|
3429
|
+
const fn = lambdaArg(a[2], c);
|
|
3430
|
+
if (!fn.ok) return fn.e;
|
|
3431
|
+
for (const v of arr.values()) {
|
|
3432
|
+
acc = fn.fn.call([acc, v]);
|
|
3433
|
+
if (acc.isError) return acc;
|
|
3434
|
+
}
|
|
3435
|
+
return acc;
|
|
3436
|
+
}
|
|
3437
|
+
function scan_(a, c) {
|
|
3438
|
+
let acc = a[0].evaluate(c);
|
|
3439
|
+
if (acc.isError) return acc;
|
|
3440
|
+
const arr = asArray(a[1].evaluate(c));
|
|
3441
|
+
const fn = lambdaArg(a[2], c);
|
|
3442
|
+
if (!fn.ok) return fn.e;
|
|
3443
|
+
const out = new ArrayValue(arr.rows, arr.columns);
|
|
3444
|
+
for (let r = 0; r < arr.rows; r++) {
|
|
3445
|
+
for (let col = 0; col < arr.columns; col++) {
|
|
3446
|
+
acc = fn.fn.call([acc, arr.get(r, col)]);
|
|
3447
|
+
out.set(r, col, acc);
|
|
3448
|
+
}
|
|
3449
|
+
}
|
|
3450
|
+
return FormulaValue.array(out);
|
|
3451
|
+
}
|
|
3452
|
+
function byRow(a, c) {
|
|
3453
|
+
const arr = asArray(a[0].evaluate(c));
|
|
3454
|
+
const fn = lambdaArg(a[1], c);
|
|
3455
|
+
if (!fn.ok) return fn.e;
|
|
3456
|
+
const out = new ArrayValue(arr.rows, 1);
|
|
3457
|
+
for (let r = 0; r < arr.rows; r++) {
|
|
3458
|
+
const row2 = new ArrayValue(1, arr.columns);
|
|
3459
|
+
for (let col = 0; col < arr.columns; col++) row2.set(0, col, arr.get(r, col));
|
|
3460
|
+
out.set(r, 0, fn.fn.call([FormulaValue.array(row2)]));
|
|
3461
|
+
}
|
|
3462
|
+
return FormulaValue.array(out);
|
|
3463
|
+
}
|
|
3464
|
+
function byCol(a, c) {
|
|
3465
|
+
const arr = asArray(a[0].evaluate(c));
|
|
3466
|
+
const fn = lambdaArg(a[1], c);
|
|
3467
|
+
if (!fn.ok) return fn.e;
|
|
3468
|
+
const out = new ArrayValue(1, arr.columns);
|
|
3469
|
+
for (let col = 0; col < arr.columns; col++) {
|
|
3470
|
+
const column2 = new ArrayValue(arr.rows, 1);
|
|
3471
|
+
for (let r = 0; r < arr.rows; r++) column2.set(r, 0, arr.get(r, col));
|
|
3472
|
+
out.set(0, col, fn.fn.call([FormulaValue.array(column2)]));
|
|
3473
|
+
}
|
|
3474
|
+
return FormulaValue.array(out);
|
|
3475
|
+
}
|
|
3476
|
+
function registerAggregate(r) {
|
|
3477
|
+
r.register("SUBTOTAL", subtotal, 2);
|
|
3478
|
+
r.register("AGGREGATE", aggregate, 3);
|
|
3479
|
+
}
|
|
3480
|
+
function collectValues(a, c, startIdx, opts) {
|
|
3481
|
+
const out = [];
|
|
3482
|
+
const ws = c.worksheet;
|
|
3483
|
+
for (let i = startIdx; i < a.length; i++) {
|
|
3484
|
+
const node = a[i];
|
|
3485
|
+
if (node instanceof RangeReferenceNode) {
|
|
3486
|
+
const b = c.getRangeBounds(node.startRef, node.endRef);
|
|
3487
|
+
for (let row2 = b.startRow; row2 <= b.endRow; row2++) {
|
|
3488
|
+
if (opts.excludeHidden && ws.isRowHidden?.(row2)) continue;
|
|
3489
|
+
for (let col = b.startCol; col <= b.endCol; col++) {
|
|
3490
|
+
const ref = cellRefFromRowCol(row2, col);
|
|
3491
|
+
if (opts.nestedPattern) {
|
|
3492
|
+
const f = ws.getCellFormula?.(ref);
|
|
3493
|
+
if (f && opts.nestedPattern.test(f)) continue;
|
|
3494
|
+
}
|
|
3495
|
+
const v = c.getCellValue(ref);
|
|
3496
|
+
if (v.isError) {
|
|
3497
|
+
if (opts.ignoreErrors) continue;
|
|
3498
|
+
return { ok: false, error: v };
|
|
3499
|
+
}
|
|
3500
|
+
out.push(v);
|
|
3501
|
+
}
|
|
3502
|
+
}
|
|
3503
|
+
} else {
|
|
3504
|
+
const v = node.evaluate(c);
|
|
3505
|
+
if (v.isError) {
|
|
3506
|
+
if (opts.ignoreErrors) continue;
|
|
3507
|
+
return { ok: false, error: v };
|
|
3508
|
+
}
|
|
3509
|
+
if (v.isArray) {
|
|
3510
|
+
for (const item of v.arrayVal.values()) {
|
|
3511
|
+
if (item.isError) {
|
|
3512
|
+
if (opts.ignoreErrors) continue;
|
|
3513
|
+
return { ok: false, error: item };
|
|
3514
|
+
}
|
|
3515
|
+
out.push(item);
|
|
3516
|
+
}
|
|
3517
|
+
} else {
|
|
3518
|
+
out.push(v);
|
|
3519
|
+
}
|
|
3520
|
+
}
|
|
3521
|
+
}
|
|
3522
|
+
return { ok: true, values: out };
|
|
3523
|
+
}
|
|
3524
|
+
function applyAggregate(fn, values, extra) {
|
|
3525
|
+
const nums = [];
|
|
3526
|
+
let countA2 = 0;
|
|
3527
|
+
for (const v of values) {
|
|
3528
|
+
if (!v.isBlank) countA2++;
|
|
3529
|
+
const r = v.tryAsDouble();
|
|
3530
|
+
if (r.ok && !v.isText && !v.isBlank) nums.push(r.value);
|
|
3531
|
+
}
|
|
3532
|
+
const sum2 = () => nums.reduce((s, n) => s + n, 0);
|
|
3533
|
+
const avg = () => nums.length ? sum2() / nums.length : NaN;
|
|
3534
|
+
const variance2 = (sample) => {
|
|
3535
|
+
const n = nums.length;
|
|
3536
|
+
if (sample ? n < 2 : n < 1) return NaN;
|
|
3537
|
+
const m = avg();
|
|
3538
|
+
const ss = nums.reduce((s, x) => s + (x - m) ** 2, 0);
|
|
3539
|
+
return ss / (sample ? n - 1 : n);
|
|
3540
|
+
};
|
|
3541
|
+
const sorted = () => [...nums].sort((x, y) => x - y);
|
|
3542
|
+
switch (fn) {
|
|
3543
|
+
case 1:
|
|
3544
|
+
return isNaN(avg()) ? FormulaValue.errorDiv0 : FormulaValue.number(avg());
|
|
3545
|
+
case 2:
|
|
3546
|
+
return FormulaValue.number(nums.length);
|
|
3547
|
+
// COUNT
|
|
3548
|
+
case 3:
|
|
3549
|
+
return FormulaValue.number(countA2);
|
|
3550
|
+
// COUNTA
|
|
3551
|
+
case 4:
|
|
3552
|
+
return nums.length ? FormulaValue.number(Math.max(...nums)) : FormulaValue.zero;
|
|
3553
|
+
case 5:
|
|
3554
|
+
return nums.length ? FormulaValue.number(Math.min(...nums)) : FormulaValue.zero;
|
|
3555
|
+
case 6:
|
|
3556
|
+
return FormulaValue.number(nums.reduce((p, n) => p * n, 1));
|
|
3557
|
+
// PRODUCT
|
|
3558
|
+
case 7: {
|
|
3559
|
+
const v = variance2(true);
|
|
3560
|
+
return isNaN(v) ? FormulaValue.errorDiv0 : FormulaValue.number(Math.sqrt(v));
|
|
3561
|
+
}
|
|
3562
|
+
// STDEV.S
|
|
3563
|
+
case 8: {
|
|
3564
|
+
const v = variance2(false);
|
|
3565
|
+
return isNaN(v) ? FormulaValue.errorDiv0 : FormulaValue.number(Math.sqrt(v));
|
|
3566
|
+
}
|
|
3567
|
+
// STDEV.P
|
|
3568
|
+
case 9:
|
|
3569
|
+
return FormulaValue.number(sum2());
|
|
3570
|
+
// SUM
|
|
3571
|
+
case 10: {
|
|
3572
|
+
const v = variance2(true);
|
|
3573
|
+
return isNaN(v) ? FormulaValue.errorDiv0 : FormulaValue.number(v);
|
|
3574
|
+
}
|
|
3575
|
+
// VAR.S
|
|
3576
|
+
case 11: {
|
|
3577
|
+
const v = variance2(false);
|
|
3578
|
+
return isNaN(v) ? FormulaValue.errorDiv0 : FormulaValue.number(v);
|
|
3579
|
+
}
|
|
3580
|
+
// VAR.P
|
|
3581
|
+
// AGGREGATE-only selectors:
|
|
3582
|
+
case 12: {
|
|
3583
|
+
const s = sorted();
|
|
3584
|
+
const m = s.length;
|
|
3585
|
+
if (!m) return FormulaValue.errorNum;
|
|
3586
|
+
const mid2 = Math.floor(m / 2);
|
|
3587
|
+
return FormulaValue.number(m % 2 ? s[mid2] : (s[mid2 - 1] + s[mid2]) / 2);
|
|
3588
|
+
}
|
|
3589
|
+
// MEDIAN
|
|
3590
|
+
case 14: {
|
|
3591
|
+
const s = sorted();
|
|
3592
|
+
const k = Math.round(extra ?? 0);
|
|
3593
|
+
return k >= 1 && k <= s.length ? FormulaValue.number(s[s.length - k]) : FormulaValue.errorNum;
|
|
3594
|
+
}
|
|
3595
|
+
case 15: {
|
|
3596
|
+
const s = sorted();
|
|
3597
|
+
const k = Math.round(extra ?? 0);
|
|
3598
|
+
return k >= 1 && k <= s.length ? FormulaValue.number(s[k - 1]) : FormulaValue.errorNum;
|
|
3599
|
+
}
|
|
3600
|
+
default:
|
|
3601
|
+
return FormulaValue.errorValue;
|
|
3602
|
+
}
|
|
3603
|
+
}
|
|
3604
|
+
function subtotal(a, c) {
|
|
3605
|
+
const fnVal = a[0].evaluate(c);
|
|
3606
|
+
if (fnVal.isError) return fnVal;
|
|
3607
|
+
const raw = fnVal.tryAsDouble();
|
|
3608
|
+
if (!raw.ok) return FormulaValue.errorValue;
|
|
3609
|
+
const code2 = Math.round(raw.value);
|
|
3610
|
+
const excludeHidden = code2 >= 101 && code2 <= 111;
|
|
3611
|
+
const fn = excludeHidden ? code2 - 100 : code2;
|
|
3612
|
+
if (fn < 1 || fn > 11) return FormulaValue.errorValue;
|
|
3613
|
+
const collected = collectValues(a, c, 1, {
|
|
3614
|
+
excludeHidden,
|
|
3615
|
+
nestedPattern: /^\s*SUBTOTAL\s*\(/i,
|
|
3616
|
+
ignoreErrors: false
|
|
3617
|
+
});
|
|
3618
|
+
if (!collected.ok) return collected.error;
|
|
3619
|
+
return applyAggregate(fn, collected.values);
|
|
3620
|
+
}
|
|
3621
|
+
function aggregate(a, c) {
|
|
3622
|
+
const fnVal = a[0].evaluate(c);
|
|
3623
|
+
if (fnVal.isError) return fnVal;
|
|
3624
|
+
const optVal = a[1].evaluate(c);
|
|
3625
|
+
if (optVal.isError) return optVal;
|
|
3626
|
+
const fnR = fnVal.tryAsDouble();
|
|
3627
|
+
const optR = optVal.tryAsDouble();
|
|
3628
|
+
if (!fnR.ok || !optR.ok) return FormulaValue.errorValue;
|
|
3629
|
+
const fn = Math.round(fnR.value);
|
|
3630
|
+
const option = Math.round(optR.value);
|
|
3631
|
+
if (fn < 1 || fn > 19) return FormulaValue.errorValue;
|
|
3632
|
+
const excludeHidden = option === 1 || option === 3 || option === 5 || option === 7;
|
|
3633
|
+
const ignoreErrors = option === 2 || option === 3 || option === 6 || option === 7;
|
|
3634
|
+
const ignoreNested = option <= 3 || option === 5 || option === 7;
|
|
3635
|
+
let extra;
|
|
3636
|
+
let endIdx = a.length;
|
|
3637
|
+
if (fn === 14 || fn === 15) {
|
|
3638
|
+
const kVal = a[a.length - 1].evaluate(c);
|
|
3639
|
+
const kR = kVal.tryAsDouble();
|
|
3640
|
+
if (!kR.ok) return FormulaValue.errorValue;
|
|
3641
|
+
extra = kR.value;
|
|
3642
|
+
endIdx = a.length - 1;
|
|
3643
|
+
}
|
|
3644
|
+
const collected = collectValues(a.slice(0, endIdx), c, 2, {
|
|
3645
|
+
excludeHidden,
|
|
3646
|
+
nestedPattern: ignoreNested ? /^\s*(SUBTOTAL|AGGREGATE)\s*\(/i : null,
|
|
3647
|
+
ignoreErrors
|
|
3648
|
+
});
|
|
3649
|
+
if (!collected.ok) return collected.error;
|
|
3650
|
+
return applyAggregate(fn, collected.values, extra);
|
|
3651
|
+
}
|
|
3652
|
+
|
|
3653
|
+
// src/functions/array-functions.ts
|
|
3654
|
+
function registerArray(r) {
|
|
3655
|
+
r.register("TRANSPOSE", transpose, 1, 1);
|
|
3656
|
+
r.register("SEQUENCE", sequence, 1, 4);
|
|
3657
|
+
r.register("UNIQUE", unique, 1, 3);
|
|
3658
|
+
r.register("SORT", sort, 1, 4);
|
|
3659
|
+
r.register("SORTBY", sortBy, 2);
|
|
3660
|
+
r.register("FILTER", filter, 2, 3);
|
|
3661
|
+
r.register("MMULT", mmult, 2, 2);
|
|
3662
|
+
r.register("TEXTSPLIT", textSplit, 2, 6);
|
|
3663
|
+
}
|
|
3664
|
+
var asArray2 = (v) => v.isArray ? v.arrayVal : ArrayValue.fromScalar(v);
|
|
3665
|
+
function fromRows(rows2) {
|
|
3666
|
+
const nr = rows2.length;
|
|
3667
|
+
const nc = nr > 0 ? rows2[0].length : 0;
|
|
3668
|
+
const arr = new ArrayValue(nr, nc);
|
|
3669
|
+
for (let r = 0; r < nr; r++) for (let c = 0; c < nc; c++) arr.set(r, c, rows2[r][c]);
|
|
3670
|
+
return FormulaValue.array(arr);
|
|
3671
|
+
}
|
|
3672
|
+
function toRows(arr) {
|
|
3673
|
+
const rows2 = [];
|
|
3674
|
+
for (let r = 0; r < arr.rows; r++) {
|
|
3675
|
+
const row2 = [];
|
|
3676
|
+
for (let c = 0; c < arr.columns; c++) row2.push(arr.get(r, c));
|
|
3677
|
+
rows2.push(row2);
|
|
3678
|
+
}
|
|
3679
|
+
return rows2;
|
|
3680
|
+
}
|
|
3681
|
+
var num4 = (a, c, i, dflt) => {
|
|
3682
|
+
if (i >= a.length) return { ok: true, n: dflt };
|
|
3683
|
+
const r = FormulaHelper.evalDouble(a[i], c);
|
|
3684
|
+
return r.ok ? { ok: true, n: r.value } : { ok: false, e: r.error };
|
|
3685
|
+
};
|
|
3686
|
+
function transpose(a, c) {
|
|
3687
|
+
const v = a[0].evaluate(c);
|
|
3688
|
+
if (v.isError) return v;
|
|
3689
|
+
return FormulaValue.array(asArray2(v).transpose());
|
|
3690
|
+
}
|
|
3691
|
+
function sequence(a, c) {
|
|
3692
|
+
const rows2 = num4(a, c, 0, 1);
|
|
3693
|
+
if (!rows2.ok) return rows2.e;
|
|
3694
|
+
const cols = num4(a, c, 1, 1);
|
|
3695
|
+
if (!cols.ok) return cols.e;
|
|
3696
|
+
const start = num4(a, c, 2, 1);
|
|
3697
|
+
if (!start.ok) return start.e;
|
|
3698
|
+
const step = num4(a, c, 3, 1);
|
|
3699
|
+
if (!step.ok) return step.e;
|
|
3700
|
+
const R = Math.trunc(rows2.n), C = Math.trunc(cols.n);
|
|
3701
|
+
if (R < 1 || C < 1) return FormulaValue.errorValue;
|
|
3702
|
+
const arr = new ArrayValue(R, C);
|
|
3703
|
+
for (let r = 0; r < R; r++) {
|
|
3704
|
+
for (let col = 0; col < C; col++) {
|
|
3705
|
+
arr.set(r, col, FormulaValue.number(start.n + (r * C + col) * step.n));
|
|
3706
|
+
}
|
|
3707
|
+
}
|
|
3708
|
+
return FormulaValue.array(arr);
|
|
3709
|
+
}
|
|
3710
|
+
function rowsEqual(x, y) {
|
|
3711
|
+
if (x.length !== y.length) return false;
|
|
3712
|
+
for (let i = 0; i < x.length; i++) if (!FormulaValue.areEqual(x[i], y[i])) return false;
|
|
3713
|
+
return true;
|
|
3714
|
+
}
|
|
3715
|
+
function unique(a, c) {
|
|
3716
|
+
const v = a[0].evaluate(c);
|
|
3717
|
+
if (v.isError) return v;
|
|
3718
|
+
const byCol2 = a.length > 1 ? a[1].evaluate(c).coerceToBool().booleanValue : false;
|
|
3719
|
+
const exactlyOnce = a.length > 2 ? a[2].evaluate(c).coerceToBool().booleanValue : false;
|
|
3720
|
+
let rows2 = toRows(byCol2 ? asArray2(v).transpose() : asArray2(v));
|
|
3721
|
+
const counts = rows2.map((r) => rows2.filter((o) => rowsEqual(o, r)).length);
|
|
3722
|
+
const seen = [];
|
|
3723
|
+
const result = [];
|
|
3724
|
+
rows2.forEach((r, i) => {
|
|
3725
|
+
if (seen.some((o) => rowsEqual(o, r))) return;
|
|
3726
|
+
seen.push(r);
|
|
3727
|
+
if (exactlyOnce && counts[i] > 1) return;
|
|
3728
|
+
result.push(r);
|
|
3729
|
+
});
|
|
3730
|
+
if (result.length === 0) return FormulaValue.error(8 /* Calc */);
|
|
3731
|
+
const out = fromRows(result);
|
|
3732
|
+
return byCol2 ? FormulaValue.array(out.arrayVal.transpose()) : out;
|
|
3733
|
+
}
|
|
3734
|
+
function sort(a, c) {
|
|
3735
|
+
const v = a[0].evaluate(c);
|
|
3736
|
+
if (v.isError) return v;
|
|
3737
|
+
const sortIndex = num4(a, c, 1, 1);
|
|
3738
|
+
if (!sortIndex.ok) return sortIndex.e;
|
|
3739
|
+
const sortOrder = num4(a, c, 2, 1);
|
|
3740
|
+
if (!sortOrder.ok) return sortOrder.e;
|
|
3741
|
+
const byCol2 = a.length > 3 ? a[3].evaluate(c).coerceToBool().booleanValue : false;
|
|
3742
|
+
const base = byCol2 ? asArray2(v).transpose() : asArray2(v);
|
|
3743
|
+
const rows2 = toRows(base);
|
|
3744
|
+
const idx = Math.trunc(sortIndex.n) - 1;
|
|
3745
|
+
const dir = sortOrder.n < 0 ? -1 : 1;
|
|
3746
|
+
if (rows2.length > 0 && (idx < 0 || idx >= rows2[0].length)) return FormulaValue.errorValue;
|
|
3747
|
+
const sorted = rows2.map((r, i) => ({ r, i })).sort((x, y) => {
|
|
3748
|
+
const cmp = FormulaValue.compare(x.r[idx], y.r[idx]) * dir;
|
|
3749
|
+
return cmp !== 0 ? cmp : x.i - y.i;
|
|
3750
|
+
}).map((o) => o.r);
|
|
3751
|
+
const out = fromRows(sorted);
|
|
3752
|
+
return byCol2 ? FormulaValue.array(out.arrayVal.transpose()) : out;
|
|
3753
|
+
}
|
|
3754
|
+
function sortBy(a, c) {
|
|
3755
|
+
const v = a[0].evaluate(c);
|
|
3756
|
+
if (v.isError) return v;
|
|
3757
|
+
const data = asArray2(v);
|
|
3758
|
+
const keys = [];
|
|
3759
|
+
let i = 1;
|
|
3760
|
+
while (i < a.length) {
|
|
3761
|
+
const byVal = a[i].evaluate(c);
|
|
3762
|
+
if (byVal.isError) return byVal;
|
|
3763
|
+
i++;
|
|
3764
|
+
let dir = 1;
|
|
3765
|
+
if (i < a.length) {
|
|
3766
|
+
const maybeOrder = a[i].evaluate(c);
|
|
3767
|
+
if (maybeOrder.isError) return maybeOrder;
|
|
3768
|
+
if (!maybeOrder.isArray && maybeOrder.isNumeric) {
|
|
3769
|
+
const d = maybeOrder.tryAsDouble();
|
|
3770
|
+
if (d.ok) {
|
|
3771
|
+
dir = d.value < 0 ? -1 : 1;
|
|
3772
|
+
i++;
|
|
3773
|
+
}
|
|
3774
|
+
}
|
|
3775
|
+
}
|
|
3776
|
+
keys.push({ vals: [...asArray2(byVal).values()], dir });
|
|
3777
|
+
}
|
|
3778
|
+
if (keys.length === 0) return FormulaValue.errorValue;
|
|
3779
|
+
const n = keys[0].vals.length;
|
|
3780
|
+
if (keys.some((k) => k.vals.length !== n)) return FormulaValue.errorValue;
|
|
3781
|
+
const byRow2 = n === data.rows;
|
|
3782
|
+
const byColumn = !byRow2 && n === data.columns;
|
|
3783
|
+
if (!byRow2 && !byColumn) return FormulaValue.errorValue;
|
|
3784
|
+
const perm = Array.from({ length: n }, (_, k) => k);
|
|
3785
|
+
perm.sort((x, y) => {
|
|
3786
|
+
for (const key of keys) {
|
|
3787
|
+
const cmp = FormulaValue.compare(key.vals[x], key.vals[y]) * key.dir;
|
|
3788
|
+
if (cmp !== 0) return cmp;
|
|
3789
|
+
}
|
|
3790
|
+
return x - y;
|
|
3791
|
+
});
|
|
3792
|
+
const out = new ArrayValue(data.rows, data.columns);
|
|
3793
|
+
if (byRow2) {
|
|
3794
|
+
for (let r = 0; r < data.rows; r++) {
|
|
3795
|
+
const src = perm[r];
|
|
3796
|
+
for (let col = 0; col < data.columns; col++) out.set(r, col, data.get(src, col));
|
|
3797
|
+
}
|
|
3798
|
+
} else {
|
|
3799
|
+
for (let col = 0; col < data.columns; col++) {
|
|
3800
|
+
const src = perm[col];
|
|
3801
|
+
for (let r = 0; r < data.rows; r++) out.set(r, col, data.get(r, src));
|
|
3802
|
+
}
|
|
3803
|
+
}
|
|
3804
|
+
return FormulaValue.array(out);
|
|
3805
|
+
}
|
|
3806
|
+
function filter(a, c) {
|
|
3807
|
+
const v = a[0].evaluate(c);
|
|
3808
|
+
if (v.isError) return v;
|
|
3809
|
+
const inc = a[1].evaluate(c);
|
|
3810
|
+
if (inc.isError) return inc;
|
|
3811
|
+
const arr = asArray2(v);
|
|
3812
|
+
const incArr = asArray2(inc);
|
|
3813
|
+
const perRow = incArr.rows === arr.rows && incArr.columns === 1;
|
|
3814
|
+
const perCol = incArr.columns === arr.columns && incArr.rows === 1;
|
|
3815
|
+
if (!perRow && !perCol) return FormulaValue.errorValue;
|
|
3816
|
+
const keptRows = [];
|
|
3817
|
+
if (perRow) {
|
|
3818
|
+
for (let r = 0; r < arr.rows; r++) {
|
|
3819
|
+
if (!incArr.get(r, 0).coerceToBool().booleanValue) continue;
|
|
3820
|
+
const row2 = [];
|
|
3821
|
+
for (let col = 0; col < arr.columns; col++) row2.push(arr.get(r, col));
|
|
3822
|
+
keptRows.push(row2);
|
|
3823
|
+
}
|
|
3824
|
+
} else {
|
|
3825
|
+
const keepCols = [];
|
|
3826
|
+
for (let col = 0; col < arr.columns; col++) {
|
|
3827
|
+
if (incArr.get(0, col).coerceToBool().booleanValue) keepCols.push(col);
|
|
3828
|
+
}
|
|
3829
|
+
for (let r = 0; r < arr.rows; r++) {
|
|
3830
|
+
keptRows.push(keepCols.map((col) => arr.get(r, col)));
|
|
3831
|
+
}
|
|
3832
|
+
if (keepCols.length === 0) keptRows.length = 0;
|
|
3833
|
+
}
|
|
3834
|
+
if (keptRows.length === 0 || keptRows[0] && keptRows[0].length === 0) {
|
|
3835
|
+
return a.length > 2 ? a[2].evaluate(c) : FormulaValue.error(8 /* Calc */);
|
|
3836
|
+
}
|
|
3837
|
+
return fromRows(keptRows);
|
|
3838
|
+
}
|
|
3839
|
+
function mmult(a, c) {
|
|
3840
|
+
const av = a[0].evaluate(c);
|
|
3841
|
+
if (av.isError) return av;
|
|
3842
|
+
const bv = a[1].evaluate(c);
|
|
3843
|
+
if (bv.isError) return bv;
|
|
3844
|
+
const A = asArray2(av), B = asArray2(bv);
|
|
3845
|
+
if (A.columns !== B.rows) return FormulaValue.errorValue;
|
|
3846
|
+
const out = new ArrayValue(A.rows, B.columns);
|
|
3847
|
+
for (let i = 0; i < A.rows; i++) {
|
|
3848
|
+
for (let j = 0; j < B.columns; j++) {
|
|
3849
|
+
let sum2 = 0;
|
|
3850
|
+
for (let k = 0; k < A.columns; k++) {
|
|
3851
|
+
const x = A.get(i, k).tryAsDouble();
|
|
3852
|
+
const y = B.get(k, j).tryAsDouble();
|
|
3853
|
+
if (!x.ok || !y.ok) return FormulaValue.errorValue;
|
|
3854
|
+
sum2 += x.value * y.value;
|
|
3855
|
+
}
|
|
3856
|
+
out.set(i, j, FormulaValue.number(sum2));
|
|
3857
|
+
}
|
|
3858
|
+
}
|
|
3859
|
+
return FormulaValue.array(out);
|
|
3860
|
+
}
|
|
3861
|
+
function textSplit(a, c) {
|
|
3862
|
+
const t = FormulaHelper.evalString(a[0], c);
|
|
3863
|
+
if (!t.ok) return t.error;
|
|
3864
|
+
const colD = FormulaHelper.evalString(a[1], c);
|
|
3865
|
+
if (!colD.ok) return colD.error;
|
|
3866
|
+
let rowD = "";
|
|
3867
|
+
if (a.length > 2) {
|
|
3868
|
+
const rd = a[2].evaluate(c);
|
|
3869
|
+
if (rd.isError) return rd;
|
|
3870
|
+
if (!rd.isBlank) {
|
|
3871
|
+
const r = FormulaHelper.evalString(a[2], c);
|
|
3872
|
+
if (!r.ok) return r.error;
|
|
3873
|
+
rowD = r.value;
|
|
3874
|
+
}
|
|
3875
|
+
}
|
|
3876
|
+
const split = (s, d) => d === "" ? [s] : s.split(d);
|
|
3877
|
+
const lines = rowD ? split(t.value, rowD) : [t.value];
|
|
3878
|
+
const grid = lines.map((line) => split(line, colD.value));
|
|
3879
|
+
const width = grid.reduce((m, r) => Math.max(m, r.length), 0);
|
|
3880
|
+
const rows2 = grid.map((r) => {
|
|
3881
|
+
const row2 = [];
|
|
3882
|
+
for (let i = 0; i < width; i++) row2.push(FormulaValue.text(r[i] ?? ""));
|
|
3883
|
+
return row2;
|
|
3884
|
+
});
|
|
3885
|
+
return fromRows(rows2);
|
|
3886
|
+
}
|
|
3887
|
+
|
|
2535
3888
|
// src/function-registry.ts
|
|
2536
3889
|
var _default, _functions, _FunctionRegistry_instances, registerBuiltIns_fn;
|
|
2537
3890
|
var _FunctionRegistry = class _FunctionRegistry {
|
|
@@ -2590,6 +3943,10 @@ registerBuiltIns_fn = function() {
|
|
|
2590
3943
|
registerLookup(this);
|
|
2591
3944
|
registerStatistical(this);
|
|
2592
3945
|
registerInfo(this);
|
|
3946
|
+
registerFinance(this);
|
|
3947
|
+
registerMeta(this);
|
|
3948
|
+
registerAggregate(this);
|
|
3949
|
+
registerArray(this);
|
|
2593
3950
|
};
|
|
2594
3951
|
__privateAdd(_FunctionRegistry, _default);
|
|
2595
3952
|
var FunctionRegistry = _FunctionRegistry;
|
|
@@ -2611,8 +3968,8 @@ var FormulaHelper;
|
|
|
2611
3968
|
FormulaHelper2.evalString = evalString;
|
|
2612
3969
|
function collectNumbers(args, ctx) {
|
|
2613
3970
|
const nums = [];
|
|
2614
|
-
for (const
|
|
2615
|
-
const v =
|
|
3971
|
+
for (const arg2 of args) {
|
|
3972
|
+
const v = arg2.evaluate(ctx);
|
|
2616
3973
|
if (v.isError) return { ok: false, error: v };
|
|
2617
3974
|
if (v.isArray) {
|
|
2618
3975
|
for (const item of v.arrayVal.values()) {
|
|
@@ -2632,8 +3989,8 @@ var FormulaHelper;
|
|
|
2632
3989
|
FormulaHelper2.collectNumbers = collectNumbers;
|
|
2633
3990
|
function flattenArgs(args, ctx) {
|
|
2634
3991
|
const result = [];
|
|
2635
|
-
for (const
|
|
2636
|
-
const v =
|
|
3992
|
+
for (const arg2 of args) {
|
|
3993
|
+
const v = arg2.evaluate(ctx);
|
|
2637
3994
|
if (v.isArray) {
|
|
2638
3995
|
for (const item of v.arrayVal.values()) result.push(item);
|
|
2639
3996
|
} else {
|
|
@@ -2671,9 +4028,9 @@ var FormulaHelper;
|
|
|
2671
4028
|
const pattern = wildcardToRegex(criteria);
|
|
2672
4029
|
return pattern.test(value2.asText());
|
|
2673
4030
|
}
|
|
2674
|
-
const
|
|
2675
|
-
if (!isNaN(
|
|
2676
|
-
return FormulaValue.areEqual(value2, FormulaValue.number(
|
|
4031
|
+
const num5 = parseFloat(criteria);
|
|
4032
|
+
if (!isNaN(num5)) {
|
|
4033
|
+
return FormulaValue.areEqual(value2, FormulaValue.number(num5));
|
|
2677
4034
|
}
|
|
2678
4035
|
return value2.asText().toUpperCase() === criteria.toUpperCase();
|
|
2679
4036
|
}
|
|
@@ -2685,18 +4042,33 @@ var FormulaHelper;
|
|
|
2685
4042
|
})(FormulaHelper || (FormulaHelper = {}));
|
|
2686
4043
|
|
|
2687
4044
|
// src/formula-context.ts
|
|
2688
|
-
var _sheet, _functions2, _evaluating;
|
|
4045
|
+
var _sheet, _functions2, _evaluating, _scopes, _FormulaContext_instances, lookupScope_fn;
|
|
2689
4046
|
var _FormulaContext = class _FormulaContext {
|
|
2690
4047
|
constructor(sheet, formulaRow = 0, formulaCol = 0, evaluating, registry) {
|
|
4048
|
+
__privateAdd(this, _FormulaContext_instances);
|
|
2691
4049
|
__privateAdd(this, _sheet);
|
|
2692
4050
|
__privateAdd(this, _functions2);
|
|
2693
4051
|
__privateAdd(this, _evaluating);
|
|
4052
|
+
/**
|
|
4053
|
+
* Lexical scope stack for LET/LAMBDA local names. Each frame maps an
|
|
4054
|
+
* upper-cased local name to its value. Names resolve innermost-first and take
|
|
4055
|
+
* precedence over workbook defined names.
|
|
4056
|
+
*/
|
|
4057
|
+
__privateAdd(this, _scopes, []);
|
|
2694
4058
|
__privateSet(this, _sheet, sheet);
|
|
2695
4059
|
this.formulaRow = formulaRow;
|
|
2696
4060
|
this.formulaCol = formulaCol;
|
|
2697
4061
|
__privateSet(this, _evaluating, evaluating ?? /* @__PURE__ */ new Set());
|
|
2698
4062
|
__privateSet(this, _functions2, registry ?? FunctionRegistry.default);
|
|
2699
4063
|
}
|
|
4064
|
+
/** Pushes a new binding frame (used by LET/LAMBDA). */
|
|
4065
|
+
pushScope(bindings) {
|
|
4066
|
+
__privateGet(this, _scopes).push(bindings);
|
|
4067
|
+
}
|
|
4068
|
+
/** Pops the innermost binding frame. */
|
|
4069
|
+
popScope() {
|
|
4070
|
+
__privateGet(this, _scopes).pop();
|
|
4071
|
+
}
|
|
2700
4072
|
get worksheet() {
|
|
2701
4073
|
return __privateGet(this, _sheet);
|
|
2702
4074
|
}
|
|
@@ -2748,8 +4120,21 @@ var _FormulaContext = class _FormulaContext {
|
|
|
2748
4120
|
return FormulaValue.errorRef;
|
|
2749
4121
|
}
|
|
2750
4122
|
}
|
|
2751
|
-
resolveNamedRange(
|
|
2752
|
-
|
|
4123
|
+
resolveNamedRange(name) {
|
|
4124
|
+
const scoped = __privateMethod(this, _FormulaContext_instances, lookupScope_fn).call(this, name);
|
|
4125
|
+
if (scoped !== void 0) return scoped;
|
|
4126
|
+
return this.nameResolver ? this.nameResolver(name) : FormulaValue.errorName;
|
|
4127
|
+
}
|
|
4128
|
+
/**
|
|
4129
|
+
* Resolves a spill-range reference (A1#) to the array spilling from the anchor
|
|
4130
|
+
* cell. Requires the worksheet to expose getSpillRange; otherwise #REF!.
|
|
4131
|
+
*/
|
|
4132
|
+
resolveSpillRange(anchorRef) {
|
|
4133
|
+
const spillRef = __privateGet(this, _sheet).getSpillRange?.(anchorRef);
|
|
4134
|
+
if (!spillRef) return FormulaValue.errorRef;
|
|
4135
|
+
const colon = spillRef.indexOf(":");
|
|
4136
|
+
if (colon < 0) return this.getCellValue(spillRef);
|
|
4137
|
+
return this.getRangeValues(spillRef.slice(0, colon), spillRef.slice(colon + 1));
|
|
2753
4138
|
}
|
|
2754
4139
|
getRangeBounds(startRef, endRef) {
|
|
2755
4140
|
const s = parseCellRef(startRef);
|
|
@@ -2757,13 +4142,34 @@ var _FormulaContext = class _FormulaContext {
|
|
|
2757
4142
|
return { startRow: s.row, startCol: s.column, endRow: e.row, endCol: e.column };
|
|
2758
4143
|
}
|
|
2759
4144
|
// ── Function dispatch ─────────────────────────────────────────────────────
|
|
4145
|
+
/** True if a built-in function with this name is registered. */
|
|
4146
|
+
hasFunction(name) {
|
|
4147
|
+
return __privateGet(this, _functions2).has(name);
|
|
4148
|
+
}
|
|
2760
4149
|
evaluateFunction(name, args) {
|
|
4150
|
+
if (!__privateGet(this, _functions2).has(name)) {
|
|
4151
|
+
const named = this.resolveNamedRange(name);
|
|
4152
|
+
if (named.isLambda) {
|
|
4153
|
+
return named.lambdaVal.call(args.map((a) => a.evaluate(this)));
|
|
4154
|
+
}
|
|
4155
|
+
}
|
|
2761
4156
|
return __privateGet(this, _functions2).execute(name, args, this);
|
|
2762
4157
|
}
|
|
2763
4158
|
};
|
|
2764
4159
|
_sheet = new WeakMap();
|
|
2765
4160
|
_functions2 = new WeakMap();
|
|
2766
4161
|
_evaluating = new WeakMap();
|
|
4162
|
+
_scopes = new WeakMap();
|
|
4163
|
+
_FormulaContext_instances = new WeakSet();
|
|
4164
|
+
lookupScope_fn = function(name) {
|
|
4165
|
+
if (__privateGet(this, _scopes).length === 0) return void 0;
|
|
4166
|
+
const key = name.toUpperCase();
|
|
4167
|
+
for (let i = __privateGet(this, _scopes).length - 1; i >= 0; i--) {
|
|
4168
|
+
const v = __privateGet(this, _scopes)[i].get(key);
|
|
4169
|
+
if (v !== void 0) return v;
|
|
4170
|
+
}
|
|
4171
|
+
return void 0;
|
|
4172
|
+
};
|
|
2767
4173
|
var FormulaContext = _FormulaContext;
|
|
2768
4174
|
|
|
2769
4175
|
// src/lru-cache.ts
|
|
@@ -2870,16 +4276,63 @@ function parseFormula(formula) {
|
|
|
2870
4276
|
astCache.set(stripped, ast);
|
|
2871
4277
|
return ast;
|
|
2872
4278
|
}
|
|
4279
|
+
var DEFAULT_LAMBDA_DEPTH = 1024;
|
|
4280
|
+
function buildContext(sheet, opts) {
|
|
4281
|
+
const evaluating = opts.evaluating ?? /* @__PURE__ */ new Set();
|
|
4282
|
+
const ctx = new FormulaContext(
|
|
4283
|
+
sheet,
|
|
4284
|
+
opts.formulaRow ?? 0,
|
|
4285
|
+
opts.formulaCol ?? 0,
|
|
4286
|
+
evaluating
|
|
4287
|
+
);
|
|
4288
|
+
ctx.recursionGuard = opts.recursionGuard ?? { depth: 0, max: DEFAULT_LAMBDA_DEPTH };
|
|
4289
|
+
const wb = opts.workbook;
|
|
4290
|
+
if (wb) {
|
|
4291
|
+
ctx.workbook = wb;
|
|
4292
|
+
if (typeof wb.getDefinedName === "function") {
|
|
4293
|
+
const resolving = opts.resolvingNames ?? /* @__PURE__ */ new Set();
|
|
4294
|
+
const resolved = opts.resolvedNames ?? /* @__PURE__ */ new Map();
|
|
4295
|
+
const guard = ctx.recursionGuard;
|
|
4296
|
+
ctx.nameResolver = (name) => resolveName(name, sheet, wb, evaluating, resolving, resolved, guard);
|
|
4297
|
+
}
|
|
4298
|
+
}
|
|
4299
|
+
return ctx;
|
|
4300
|
+
}
|
|
4301
|
+
function resolveName(name, sheet, workbook, evaluating, resolving, resolved, recursionGuard) {
|
|
4302
|
+
const key = `${sheet.name}\0${name.toUpperCase()}`;
|
|
4303
|
+
const cached = resolved.get(key);
|
|
4304
|
+
if (cached !== void 0) return cached;
|
|
4305
|
+
if (resolving.has(key)) return FormulaValue.errorRef;
|
|
4306
|
+
const refersTo = workbook.getDefinedName(name, sheet.name);
|
|
4307
|
+
if (refersTo == null || refersTo === "") return FormulaValue.errorName;
|
|
4308
|
+
resolving.add(key);
|
|
4309
|
+
try {
|
|
4310
|
+
const ast = parseFormula(refersTo);
|
|
4311
|
+
const ctx = buildContext(sheet, {
|
|
4312
|
+
workbook,
|
|
4313
|
+
evaluating,
|
|
4314
|
+
resolvingNames: resolving,
|
|
4315
|
+
resolvedNames: resolved,
|
|
4316
|
+
recursionGuard
|
|
4317
|
+
});
|
|
4318
|
+
const value2 = ast.evaluate(ctx);
|
|
4319
|
+
if (value2.isLambda) resolved.set(key, value2);
|
|
4320
|
+
return value2;
|
|
4321
|
+
} catch {
|
|
4322
|
+
return FormulaValue.errorName;
|
|
4323
|
+
} finally {
|
|
4324
|
+
resolving.delete(key);
|
|
4325
|
+
}
|
|
4326
|
+
}
|
|
2873
4327
|
function evaluateFormula(formula, sheet, options) {
|
|
2874
4328
|
if (!formula) return FormulaValue.blank;
|
|
2875
4329
|
try {
|
|
2876
4330
|
const ast = parseFormula(formula);
|
|
2877
|
-
const ctx =
|
|
2878
|
-
|
|
2879
|
-
options?.formulaRow
|
|
2880
|
-
options?.formulaCol
|
|
2881
|
-
);
|
|
2882
|
-
if (options?.workbook) ctx.workbook = options.workbook;
|
|
4331
|
+
const ctx = buildContext(sheet, {
|
|
4332
|
+
workbook: options?.workbook,
|
|
4333
|
+
formulaRow: options?.formulaRow,
|
|
4334
|
+
formulaCol: options?.formulaCol
|
|
4335
|
+
});
|
|
2883
4336
|
return ast.evaluate(ctx);
|
|
2884
4337
|
} catch {
|
|
2885
4338
|
return FormulaValue.errorValue;
|
|
@@ -2899,7 +4352,439 @@ function getAstCacheStats() {
|
|
|
2899
4352
|
function setAstCacheCapacity(capacity) {
|
|
2900
4353
|
astCache.resize(capacity);
|
|
2901
4354
|
}
|
|
4355
|
+
function extractReferences(ast, formulaSheet, registry = FunctionRegistry.default, resolveName2) {
|
|
4356
|
+
const refs = [];
|
|
4357
|
+
let volatile = false;
|
|
4358
|
+
const seenNames = /* @__PURE__ */ new Set();
|
|
4359
|
+
const cell = (sheet, ref) => {
|
|
4360
|
+
const { row: row2, column: column2 } = parseCellRef(ref);
|
|
4361
|
+
return { sheet: sheet.toUpperCase(), startRow: row2, startCol: column2, endRow: row2, endCol: column2 };
|
|
4362
|
+
};
|
|
4363
|
+
const range = (sheet, startRef, endRef) => {
|
|
4364
|
+
const s = parseCellRef(startRef);
|
|
4365
|
+
const e = parseCellRef(endRef);
|
|
4366
|
+
return {
|
|
4367
|
+
sheet: sheet.toUpperCase(),
|
|
4368
|
+
startRow: Math.min(s.row, e.row),
|
|
4369
|
+
startCol: Math.min(s.column, e.column),
|
|
4370
|
+
endRow: Math.max(s.row, e.row),
|
|
4371
|
+
endCol: Math.max(s.column, e.column)
|
|
4372
|
+
};
|
|
4373
|
+
};
|
|
4374
|
+
const walk = (node) => {
|
|
4375
|
+
if (node instanceof CellReferenceNode) {
|
|
4376
|
+
refs.push(cell(formulaSheet, node.reference));
|
|
4377
|
+
} else if (node instanceof RangeReferenceNode) {
|
|
4378
|
+
refs.push(range(formulaSheet, node.startRef, node.endRef));
|
|
4379
|
+
} else if (node instanceof SheetCellReferenceNode) {
|
|
4380
|
+
refs.push(cell(node.sheetName, node.cellReference));
|
|
4381
|
+
} else if (node instanceof SheetRangeReferenceNode) {
|
|
4382
|
+
refs.push(range(node.sheetName, node.startRef, node.endRef));
|
|
4383
|
+
} else if (node instanceof NamedRangeNode) {
|
|
4384
|
+
expandName(node.name);
|
|
4385
|
+
} else if (node instanceof SpillReferenceNode) {
|
|
4386
|
+
refs.push(cell(formulaSheet, node.anchorRef));
|
|
4387
|
+
} else if (node instanceof FunctionCallNode) {
|
|
4388
|
+
if (registry.isVolatile(node.functionName)) volatile = true;
|
|
4389
|
+
for (const arg2 of node.args) walk(arg2);
|
|
4390
|
+
} else if (node instanceof BinaryOpNode) {
|
|
4391
|
+
walk(node.left);
|
|
4392
|
+
walk(node.right);
|
|
4393
|
+
} else if (node instanceof UnaryOpNode) {
|
|
4394
|
+
walk(node.operand);
|
|
4395
|
+
} else if (node instanceof ImplicitIntersectionNode) {
|
|
4396
|
+
walk(node.inner);
|
|
4397
|
+
}
|
|
4398
|
+
};
|
|
4399
|
+
const expandName = (name) => {
|
|
4400
|
+
if (!resolveName2) return;
|
|
4401
|
+
const key = name.toUpperCase();
|
|
4402
|
+
if (seenNames.has(key)) return;
|
|
4403
|
+
seenNames.add(key);
|
|
4404
|
+
const refersTo = resolveName2(name, formulaSheet);
|
|
4405
|
+
if (!refersTo) return;
|
|
4406
|
+
try {
|
|
4407
|
+
walk(parseFormula(refersTo));
|
|
4408
|
+
} catch {
|
|
4409
|
+
}
|
|
4410
|
+
};
|
|
4411
|
+
walk(ast);
|
|
4412
|
+
return { refs, volatile };
|
|
4413
|
+
}
|
|
4414
|
+
function refContains(ref, sheet, row2, col) {
|
|
4415
|
+
return ref.sheet === sheet && row2 >= ref.startRow && row2 <= ref.endRow && col >= ref.startCol && col <= ref.endCol;
|
|
4416
|
+
}
|
|
4417
|
+
|
|
4418
|
+
// src/recalc-engine.ts
|
|
4419
|
+
function createWorkbookRecalcModel(workbook) {
|
|
4420
|
+
return {
|
|
4421
|
+
getCellValue: (sheet, ref) => workbook.getWorksheet(sheet).getCellValue(ref),
|
|
4422
|
+
setCellValue: (sheet, ref, value2) => {
|
|
4423
|
+
workbook.getWorksheet(sheet).getCell(ref).setComputedValue(value2);
|
|
4424
|
+
},
|
|
4425
|
+
setCellFormula: (sheet, ref, formula) => {
|
|
4426
|
+
workbook.getWorksheet(sheet).getCell(ref).setFormula(formula);
|
|
4427
|
+
},
|
|
4428
|
+
clearCell: (sheet, ref) => {
|
|
4429
|
+
workbook.getWorksheet(sheet).getCell(ref).clear();
|
|
4430
|
+
},
|
|
4431
|
+
setCellArrayRef: (sheet, ref, spillRef) => {
|
|
4432
|
+
workbook.getWorksheet(sheet).getCell(ref).setArrayRef(spillRef);
|
|
4433
|
+
},
|
|
4434
|
+
getCellFormula: (sheet, ref) => workbook.getWorksheet(sheet).getCellFormula?.(ref) ?? null,
|
|
4435
|
+
getSpillRange: (sheet, ref) => workbook.getWorksheet(sheet).getSpillRange?.(ref) ?? null,
|
|
4436
|
+
isRowHidden: (sheet, row2) => workbook.getWorksheet(sheet).isRowHidden?.(row2) ?? false,
|
|
4437
|
+
getDefinedName: (name, sheet) => workbook.getDefinedName(name, sheet)
|
|
4438
|
+
};
|
|
4439
|
+
}
|
|
4440
|
+
var normSheet = (s) => s.toUpperCase();
|
|
4441
|
+
var normRef = (r) => r.replace(/\$/g, "").toUpperCase();
|
|
4442
|
+
var keyOf = (sheet, ref) => `${normSheet(sheet)}!${normRef(ref)}`;
|
|
4443
|
+
function parseKey(key) {
|
|
4444
|
+
const bang = key.indexOf("!");
|
|
4445
|
+
const sheet = key.slice(0, bang);
|
|
4446
|
+
const ref = key.slice(bang + 1);
|
|
4447
|
+
const { row: row2, column: column2 } = parseCellRef(ref);
|
|
4448
|
+
return { sheet, ref, row: row2, col: column2 };
|
|
4449
|
+
}
|
|
4450
|
+
var _model, _registry, _formulas, _sheetNames, _spills, _spillOwner, _RecalcEngine_instances, rememberSheet_fn, recalcFrom_fn, dependentClosure_fn, directDependents_fn, evaluatePass_fn, writeResult_fn, isOccupied_fn, clearSpill_fn, evaluateFormulaValue_fn, sheetLike_fn, buildWorkbookLike_fn;
|
|
4451
|
+
var RecalcEngine = class {
|
|
4452
|
+
constructor(model, registry = FunctionRegistry.default) {
|
|
4453
|
+
__privateAdd(this, _RecalcEngine_instances);
|
|
4454
|
+
__privateAdd(this, _model);
|
|
4455
|
+
__privateAdd(this, _registry);
|
|
4456
|
+
__privateAdd(this, _formulas, /* @__PURE__ */ new Map());
|
|
4457
|
+
/** upper-cased sheet key → original casing, for case-correct model I/O. */
|
|
4458
|
+
__privateAdd(this, _sheetNames, /* @__PURE__ */ new Map());
|
|
4459
|
+
/** anchor cellKey → set of spilled (non-anchor) cellKeys it currently owns. */
|
|
4460
|
+
__privateAdd(this, _spills, /* @__PURE__ */ new Map());
|
|
4461
|
+
/** spilled cellKey → the anchor cellKey that owns it. */
|
|
4462
|
+
__privateAdd(this, _spillOwner, /* @__PURE__ */ new Map());
|
|
4463
|
+
__privateSet(this, _model, model);
|
|
4464
|
+
__privateSet(this, _registry, registry);
|
|
4465
|
+
}
|
|
4466
|
+
// ── Registration ─────────────────────────────────────────────────────────────
|
|
4467
|
+
/**
|
|
4468
|
+
* Registers (or replaces) a formula for a cell and recalculates that cell and
|
|
4469
|
+
* everything downstream of it. Returns the recomputed cells in the order they
|
|
4470
|
+
* were evaluated. The leading '=' of the formula is optional.
|
|
4471
|
+
*/
|
|
4472
|
+
setCellFormula(sheet, ref, formula) {
|
|
4473
|
+
if (!formula) throw new Error("Formula cannot be empty.");
|
|
4474
|
+
const text = formula.startsWith("=") ? formula.slice(1) : formula;
|
|
4475
|
+
const s = normSheet(sheet);
|
|
4476
|
+
const r = normRef(ref);
|
|
4477
|
+
const { row: row2, column: column2 } = parseCellRef(r);
|
|
4478
|
+
const ast = parseFormula(text);
|
|
4479
|
+
const { refs, volatile } = extractReferences(
|
|
4480
|
+
ast,
|
|
4481
|
+
s,
|
|
4482
|
+
__privateGet(this, _registry),
|
|
4483
|
+
__privateGet(this, _model).getDefinedName ? (n, sh) => __privateGet(this, _model).getDefinedName(n, sh) : void 0
|
|
4484
|
+
);
|
|
4485
|
+
__privateMethod(this, _RecalcEngine_instances, rememberSheet_fn).call(this, sheet);
|
|
4486
|
+
__privateGet(this, _formulas).set(keyOf(s, r), {
|
|
4487
|
+
sheet: s,
|
|
4488
|
+
sheetName: sheet,
|
|
4489
|
+
ref: r,
|
|
4490
|
+
row: row2,
|
|
4491
|
+
col: column2,
|
|
4492
|
+
formula: text,
|
|
4493
|
+
refs,
|
|
4494
|
+
volatile
|
|
4495
|
+
});
|
|
4496
|
+
__privateGet(this, _model).setCellFormula?.(sheet, r, text);
|
|
4497
|
+
return __privateMethod(this, _RecalcEngine_instances, recalcFrom_fn).call(this, [{ sheet: s, row: row2, col: column2 }], keyOf(s, r));
|
|
4498
|
+
}
|
|
4499
|
+
/**
|
|
4500
|
+
* Removes a formula from a cell and recalculates its dependents (which may now
|
|
4501
|
+
* read a plain input value instead). Returns the recomputed dependent cells.
|
|
4502
|
+
*/
|
|
4503
|
+
clearCellFormula(sheet, ref) {
|
|
4504
|
+
const s = normSheet(sheet);
|
|
4505
|
+
const r = normRef(ref);
|
|
4506
|
+
const existed = __privateGet(this, _formulas).delete(keyOf(s, r));
|
|
4507
|
+
if (!existed) return [];
|
|
4508
|
+
__privateGet(this, _model).clearCell?.(sheet, r);
|
|
4509
|
+
const { row: row2, column: column2 } = parseCellRef(r);
|
|
4510
|
+
return __privateMethod(this, _RecalcEngine_instances, recalcFrom_fn).call(this, [{ sheet: s, row: row2, col: column2 }]);
|
|
4511
|
+
}
|
|
4512
|
+
/**
|
|
4513
|
+
* Writes a raw input value to a cell and recalculates every formula that
|
|
4514
|
+
* depends on it. Use this for non-formula edits so dependents stay current.
|
|
4515
|
+
*/
|
|
4516
|
+
setCellValue(sheet, ref, value2) {
|
|
4517
|
+
__privateMethod(this, _RecalcEngine_instances, rememberSheet_fn).call(this, sheet);
|
|
4518
|
+
const s = normSheet(sheet);
|
|
4519
|
+
const r = normRef(ref);
|
|
4520
|
+
__privateGet(this, _model).setCellValue(sheet, r, value2);
|
|
4521
|
+
const { row: row2, column: column2 } = parseCellRef(r);
|
|
4522
|
+
return __privateMethod(this, _RecalcEngine_instances, recalcFrom_fn).call(this, [{ sheet: s, row: row2, col: column2 }]);
|
|
4523
|
+
}
|
|
4524
|
+
/**
|
|
4525
|
+
* Signals that a cell changed by some external means (the model was already
|
|
4526
|
+
* updated) and recalculates its dependents.
|
|
4527
|
+
*/
|
|
4528
|
+
onCellChanged(sheet, ref) {
|
|
4529
|
+
__privateMethod(this, _RecalcEngine_instances, rememberSheet_fn).call(this, sheet);
|
|
4530
|
+
const s = normSheet(sheet);
|
|
4531
|
+
const r = normRef(ref);
|
|
4532
|
+
const { row: row2, column: column2 } = parseCellRef(r);
|
|
4533
|
+
return __privateMethod(this, _RecalcEngine_instances, recalcFrom_fn).call(this, [{ sheet: s, row: row2, col: column2 }]);
|
|
4534
|
+
}
|
|
4535
|
+
/** Recalculates every registered formula in dependency order. */
|
|
4536
|
+
recalcAll() {
|
|
4537
|
+
return __privateMethod(this, _RecalcEngine_instances, evaluatePass_fn).call(this, [...__privateGet(this, _formulas).values()]).results;
|
|
4538
|
+
}
|
|
4539
|
+
/** The precedents recorded for a formula cell (mainly for tests/inspection). */
|
|
4540
|
+
getPrecedents(sheet, ref) {
|
|
4541
|
+
return __privateGet(this, _formulas).get(keyOf(sheet, ref))?.refs ?? [];
|
|
4542
|
+
}
|
|
4543
|
+
};
|
|
4544
|
+
_model = new WeakMap();
|
|
4545
|
+
_registry = new WeakMap();
|
|
4546
|
+
_formulas = new WeakMap();
|
|
4547
|
+
_sheetNames = new WeakMap();
|
|
4548
|
+
_spills = new WeakMap();
|
|
4549
|
+
_spillOwner = new WeakMap();
|
|
4550
|
+
_RecalcEngine_instances = new WeakSet();
|
|
4551
|
+
rememberSheet_fn = function(name) {
|
|
4552
|
+
__privateGet(this, _sheetNames).set(normSheet(name), name);
|
|
4553
|
+
};
|
|
4554
|
+
// ── Internals ────────────────────────────────────────────────────────────────
|
|
4555
|
+
/**
|
|
4556
|
+
* Recomputes formulas affected by the given changed cells, to a fixpoint.
|
|
4557
|
+
*
|
|
4558
|
+
* A single topological pass is not enough once dynamic arrays exist: a
|
|
4559
|
+
* formula that spills changes cells the graph could not know about until the
|
|
4560
|
+
* array was computed, and those cells may have their own dependents. So we
|
|
4561
|
+
* evaluate a pass, collect every cell whose value actually changed (formula
|
|
4562
|
+
* outputs plus spilled/cleared cells), then recompute the dependents of those
|
|
4563
|
+
* cells, repeating until nothing new is affected (bounded for safety).
|
|
4564
|
+
*/
|
|
4565
|
+
recalcFrom_fn = function(seeds, includeKey) {
|
|
4566
|
+
const results = [];
|
|
4567
|
+
const evaluated = /* @__PURE__ */ new Set();
|
|
4568
|
+
let pending = __privateMethod(this, _RecalcEngine_instances, dependentClosure_fn).call(this, seeds, evaluated);
|
|
4569
|
+
for (const e of __privateGet(this, _formulas).values()) {
|
|
4570
|
+
if (e.volatile) pending.set(keyOf(e.sheet, e.ref), e);
|
|
4571
|
+
}
|
|
4572
|
+
if (includeKey) {
|
|
4573
|
+
const self = __privateGet(this, _formulas).get(includeKey);
|
|
4574
|
+
if (self) pending.set(includeKey, self);
|
|
4575
|
+
}
|
|
4576
|
+
let guard = 0;
|
|
4577
|
+
const maxIterations = __privateGet(this, _formulas).size + 8;
|
|
4578
|
+
while (pending.size > 0 && guard++ <= maxIterations) {
|
|
4579
|
+
const { results: passResults, changed } = __privateMethod(this, _RecalcEngine_instances, evaluatePass_fn).call(this, [...pending.values()]);
|
|
4580
|
+
results.push(...passResults);
|
|
4581
|
+
for (const k of pending.keys()) evaluated.add(k);
|
|
4582
|
+
pending = __privateMethod(this, _RecalcEngine_instances, dependentClosure_fn).call(this, changed, evaluated);
|
|
4583
|
+
}
|
|
4584
|
+
return results;
|
|
4585
|
+
};
|
|
4586
|
+
/** Formula entries (not yet evaluated) whose precedents include one of the cells. */
|
|
4587
|
+
dependentClosure_fn = function(cells, evaluated) {
|
|
4588
|
+
const out = /* @__PURE__ */ new Map();
|
|
4589
|
+
const queue = [...cells];
|
|
4590
|
+
while (queue.length > 0) {
|
|
4591
|
+
const cell = queue.shift();
|
|
4592
|
+
for (const dep of __privateMethod(this, _RecalcEngine_instances, directDependents_fn).call(this, cell)) {
|
|
4593
|
+
const k = keyOf(dep.sheet, dep.ref);
|
|
4594
|
+
if (out.has(k) || evaluated.has(k)) continue;
|
|
4595
|
+
out.set(k, dep);
|
|
4596
|
+
queue.push({ sheet: dep.sheet, row: dep.row, col: dep.col });
|
|
4597
|
+
}
|
|
4598
|
+
}
|
|
4599
|
+
return out;
|
|
4600
|
+
};
|
|
4601
|
+
/** Formula entries whose precedents include the given cell. */
|
|
4602
|
+
directDependents_fn = function(cell) {
|
|
4603
|
+
const out = [];
|
|
4604
|
+
for (const e of __privateGet(this, _formulas).values()) {
|
|
4605
|
+
if (e.refs.some((ref) => refContains(ref, cell.sheet, cell.row, cell.col))) out.push(e);
|
|
4606
|
+
}
|
|
4607
|
+
return out;
|
|
4608
|
+
};
|
|
4609
|
+
/**
|
|
4610
|
+
* Topologically sorts the given entries and evaluates them, writing results
|
|
4611
|
+
* (scalars or spilled arrays) back to the model. Returns the results and the
|
|
4612
|
+
* flat list of cells whose value changed. Entries left in a cycle are #REF!.
|
|
4613
|
+
*/
|
|
4614
|
+
evaluatePass_fn = function(entries) {
|
|
4615
|
+
const inSet = /* @__PURE__ */ new Map();
|
|
4616
|
+
for (const e of entries) inSet.set(keyOf(e.sheet, e.ref), e);
|
|
4617
|
+
const indegree = /* @__PURE__ */ new Map();
|
|
4618
|
+
const dependents = /* @__PURE__ */ new Map();
|
|
4619
|
+
for (const k of inSet.keys()) {
|
|
4620
|
+
indegree.set(k, 0);
|
|
4621
|
+
dependents.set(k, []);
|
|
4622
|
+
}
|
|
4623
|
+
for (const e of entries) {
|
|
4624
|
+
const depKey = keyOf(e.sheet, e.ref);
|
|
4625
|
+
for (const [pk, pe] of inSet) {
|
|
4626
|
+
if (pk === depKey) continue;
|
|
4627
|
+
if (e.refs.some((ref) => refContains(ref, pe.sheet, pe.row, pe.col))) {
|
|
4628
|
+
dependents.get(pk).push(depKey);
|
|
4629
|
+
indegree.set(depKey, indegree.get(depKey) + 1);
|
|
4630
|
+
}
|
|
4631
|
+
}
|
|
4632
|
+
}
|
|
4633
|
+
const ready = [];
|
|
4634
|
+
for (const [k, d] of indegree) if (d === 0) ready.push(k);
|
|
4635
|
+
const order = [];
|
|
4636
|
+
while (ready.length > 0) {
|
|
4637
|
+
const k = ready.shift();
|
|
4638
|
+
order.push(k);
|
|
4639
|
+
for (const d of dependents.get(k)) {
|
|
4640
|
+
indegree.set(d, indegree.get(d) - 1);
|
|
4641
|
+
if (indegree.get(d) === 0) ready.push(d);
|
|
4642
|
+
}
|
|
4643
|
+
}
|
|
4644
|
+
const results = [];
|
|
4645
|
+
const changed = [];
|
|
4646
|
+
const emitted = new Set(order);
|
|
4647
|
+
for (const k of order) {
|
|
4648
|
+
const e = inSet.get(k);
|
|
4649
|
+
const { result, changed: c } = __privateMethod(this, _RecalcEngine_instances, writeResult_fn).call(this, e);
|
|
4650
|
+
results.push(result);
|
|
4651
|
+
changed.push(...c);
|
|
4652
|
+
}
|
|
4653
|
+
for (const [k, e] of inSet) {
|
|
4654
|
+
if (emitted.has(k)) continue;
|
|
4655
|
+
__privateMethod(this, _RecalcEngine_instances, clearSpill_fn).call(this, keyOf(e.sheet, e.ref), changed);
|
|
4656
|
+
const value2 = FormulaValue.errorRef.toObject();
|
|
4657
|
+
__privateGet(this, _model).setCellValue(e.sheetName, e.ref, value2);
|
|
4658
|
+
changed.push({ sheet: e.sheet, row: e.row, col: e.col });
|
|
4659
|
+
results.push({ sheet: e.sheetName, ref: e.ref, value: value2, circular: true });
|
|
4660
|
+
}
|
|
4661
|
+
return { results, changed };
|
|
4662
|
+
};
|
|
4663
|
+
/**
|
|
4664
|
+
* Evaluates one formula and writes its result. Scalars go to the anchor cell.
|
|
4665
|
+
* Arrays spill across a block anchored at the formula cell: on a collision
|
|
4666
|
+
* with existing content the anchor becomes #SPILL! and nothing spills; when
|
|
4667
|
+
* an array shrinks, previously-spilled cells it no longer covers are cleared.
|
|
4668
|
+
*/
|
|
4669
|
+
writeResult_fn = function(e) {
|
|
4670
|
+
const anchorKey = keyOf(e.sheet, e.ref);
|
|
4671
|
+
const fv2 = __privateMethod(this, _RecalcEngine_instances, evaluateFormulaValue_fn).call(this, e);
|
|
4672
|
+
const changed = [];
|
|
4673
|
+
const prevSpill = __privateGet(this, _spills).get(anchorKey) ?? /* @__PURE__ */ new Set();
|
|
4674
|
+
if (!fv2.isArray) {
|
|
4675
|
+
__privateMethod(this, _RecalcEngine_instances, clearSpill_fn).call(this, anchorKey, changed);
|
|
4676
|
+
__privateGet(this, _model).setCellArrayRef?.(e.sheetName, e.ref, null);
|
|
4677
|
+
const value2 = fv2.toObject();
|
|
4678
|
+
__privateGet(this, _model).setCellValue(e.sheetName, e.ref, value2);
|
|
4679
|
+
changed.push({ sheet: e.sheet, row: e.row, col: e.col });
|
|
4680
|
+
return { result: { sheet: e.sheetName, ref: e.ref, value: value2 }, changed };
|
|
4681
|
+
}
|
|
4682
|
+
const arr = fv2.arrayVal;
|
|
4683
|
+
const rows2 = arr.rows, cols = arr.columns;
|
|
4684
|
+
let collides = false;
|
|
4685
|
+
for (let dr = 0; dr < rows2 && !collides; dr++) {
|
|
4686
|
+
for (let dc = 0; dc < cols && !collides; dc++) {
|
|
4687
|
+
if (dr === 0 && dc === 0) continue;
|
|
4688
|
+
const r = e.row + dr, c = e.col + dc;
|
|
4689
|
+
const cellKey = keyOf(e.sheet, cellRefFromRowCol(r, c));
|
|
4690
|
+
if (__privateMethod(this, _RecalcEngine_instances, isOccupied_fn).call(this, cellKey, e.sheetName, cellRefFromRowCol(r, c), anchorKey, prevSpill)) {
|
|
4691
|
+
collides = true;
|
|
4692
|
+
}
|
|
4693
|
+
}
|
|
4694
|
+
}
|
|
4695
|
+
if (collides) {
|
|
4696
|
+
__privateMethod(this, _RecalcEngine_instances, clearSpill_fn).call(this, anchorKey, changed);
|
|
4697
|
+
__privateGet(this, _model).setCellArrayRef?.(e.sheetName, e.ref, null);
|
|
4698
|
+
const value2 = FormulaValue.error(9 /* Spill */).toObject();
|
|
4699
|
+
__privateGet(this, _model).setCellValue(e.sheetName, e.ref, value2);
|
|
4700
|
+
changed.push({ sheet: e.sheet, row: e.row, col: e.col });
|
|
4701
|
+
return { result: { sheet: e.sheetName, ref: e.ref, value: value2 }, changed };
|
|
4702
|
+
}
|
|
4703
|
+
const newSpill = /* @__PURE__ */ new Set();
|
|
4704
|
+
for (let dr = 0; dr < rows2; dr++) {
|
|
4705
|
+
for (let dc = 0; dc < cols; dc++) {
|
|
4706
|
+
const r = e.row + dr, c = e.col + dc;
|
|
4707
|
+
const ref = cellRefFromRowCol(r, c);
|
|
4708
|
+
__privateGet(this, _model).setCellValue(e.sheetName, ref, arr.get(dr, dc).toObject());
|
|
4709
|
+
changed.push({ sheet: e.sheet, row: r, col: c });
|
|
4710
|
+
if (dr !== 0 || dc !== 0) {
|
|
4711
|
+
const cellKey = keyOf(e.sheet, ref);
|
|
4712
|
+
newSpill.add(cellKey);
|
|
4713
|
+
__privateGet(this, _spillOwner).set(cellKey, anchorKey);
|
|
4714
|
+
}
|
|
4715
|
+
}
|
|
4716
|
+
}
|
|
4717
|
+
for (const oldKey of prevSpill) {
|
|
4718
|
+
if (newSpill.has(oldKey)) continue;
|
|
4719
|
+
const cell = parseKey(oldKey);
|
|
4720
|
+
__privateGet(this, _model).setCellValue(__privateGet(this, _sheetNames).get(cell.sheet) ?? cell.sheet, cell.ref, null);
|
|
4721
|
+
__privateGet(this, _spillOwner).delete(oldKey);
|
|
4722
|
+
changed.push({ sheet: cell.sheet, row: cell.row, col: cell.col });
|
|
4723
|
+
}
|
|
4724
|
+
__privateGet(this, _spills).set(anchorKey, newSpill);
|
|
4725
|
+
const spillRef = `${e.ref}:${cellRefFromRowCol(e.row + rows2 - 1, e.col + cols - 1)}`;
|
|
4726
|
+
__privateGet(this, _model).setCellArrayRef?.(e.sheetName, e.ref, spillRef);
|
|
4727
|
+
return {
|
|
4728
|
+
result: { sheet: e.sheetName, ref: e.ref, value: arr.get(0, 0).toObject(), spill: { rows: rows2, cols } },
|
|
4729
|
+
changed
|
|
4730
|
+
};
|
|
4731
|
+
};
|
|
4732
|
+
/** Whether a target cell already holds content that blocks a spill. */
|
|
4733
|
+
isOccupied_fn = function(cellKey, sheetName, ref, anchorKey, prevSpill) {
|
|
4734
|
+
if (__privateGet(this, _formulas).has(cellKey) && cellKey !== anchorKey) return true;
|
|
4735
|
+
const owner = __privateGet(this, _spillOwner).get(cellKey);
|
|
4736
|
+
if (owner && owner !== anchorKey) return true;
|
|
4737
|
+
if (prevSpill.has(cellKey)) return false;
|
|
4738
|
+
const v = __privateGet(this, _model).getCellValue(sheetName, ref);
|
|
4739
|
+
return v !== null && v !== void 0 && v !== "";
|
|
4740
|
+
};
|
|
4741
|
+
/** Clears an anchor's spilled cells (not the anchor itself) and forgets them. */
|
|
4742
|
+
clearSpill_fn = function(anchorKey, changed) {
|
|
4743
|
+
const spill = __privateGet(this, _spills).get(anchorKey);
|
|
4744
|
+
if (!spill) return;
|
|
4745
|
+
for (const cellKey of spill) {
|
|
4746
|
+
const cell = parseKey(cellKey);
|
|
4747
|
+
__privateGet(this, _model).setCellValue(__privateGet(this, _sheetNames).get(cell.sheet) ?? cell.sheet, cell.ref, null);
|
|
4748
|
+
__privateGet(this, _spillOwner).delete(cellKey);
|
|
4749
|
+
changed.push({ sheet: cell.sheet, row: cell.row, col: cell.col });
|
|
4750
|
+
}
|
|
4751
|
+
__privateGet(this, _spills).delete(anchorKey);
|
|
4752
|
+
};
|
|
4753
|
+
evaluateFormulaValue_fn = function(e) {
|
|
4754
|
+
const wb = __privateMethod(this, _RecalcEngine_instances, buildWorkbookLike_fn).call(this);
|
|
4755
|
+
const ws = __privateMethod(this, _RecalcEngine_instances, sheetLike_fn).call(this, e.sheetName);
|
|
4756
|
+
return evaluateFormula(e.formula, ws, {
|
|
4757
|
+
workbook: wb,
|
|
4758
|
+
formulaRow: e.row,
|
|
4759
|
+
formulaCol: e.col
|
|
4760
|
+
});
|
|
4761
|
+
};
|
|
4762
|
+
sheetLike_fn = function(sheetName) {
|
|
4763
|
+
return {
|
|
4764
|
+
name: sheetName,
|
|
4765
|
+
getCellValue: (ref) => __privateGet(this, _model).getCellValue(sheetName, ref),
|
|
4766
|
+
isRowHidden: __privateGet(this, _model).isRowHidden ? (row2) => __privateGet(this, _model).isRowHidden(sheetName, row2) : void 0,
|
|
4767
|
+
getCellFormula: __privateGet(this, _model).getCellFormula ? (ref) => __privateGet(this, _model).getCellFormula(sheetName, ref) : void 0,
|
|
4768
|
+
getSpillRange: __privateGet(this, _model).getSpillRange ? (ref) => __privateGet(this, _model).getSpillRange(sheetName, ref) : void 0
|
|
4769
|
+
};
|
|
4770
|
+
};
|
|
4771
|
+
buildWorkbookLike_fn = function() {
|
|
4772
|
+
const self = this;
|
|
4773
|
+
return {
|
|
4774
|
+
get worksheets() {
|
|
4775
|
+
return [...__privateGet(self, _sheetNames).values()].map((n) => {
|
|
4776
|
+
var _a;
|
|
4777
|
+
return __privateMethod(_a = self, _RecalcEngine_instances, sheetLike_fn).call(_a, n);
|
|
4778
|
+
});
|
|
4779
|
+
},
|
|
4780
|
+
getWorksheet: (name) => {
|
|
4781
|
+
var _a;
|
|
4782
|
+
return __privateMethod(_a = self, _RecalcEngine_instances, sheetLike_fn).call(_a, name);
|
|
4783
|
+
},
|
|
4784
|
+
getDefinedName: __privateGet(this, _model).getDefinedName ? (name, sheet) => __privateGet(this, _model).getDefinedName(name, sheet) : void 0
|
|
4785
|
+
};
|
|
4786
|
+
};
|
|
2902
4787
|
|
|
2903
|
-
export { ArrayValue, BinaryOpNode, BinaryOperator, BlankNode, BooleanNode, CellReferenceNode, ErrorNode, FormulaContext, FormulaError, FormulaException, FormulaHelper, FormulaLexer, FormulaNode, FormulaParser, FormulaValue, FunctionCallNode, FunctionRegistry, ImplicitIntersectionNode, LruCache, NamedRangeNode, NumberNode, RangeReferenceNode, SheetCellReferenceNode, SheetRangeReferenceNode, StringNode, TokenType, UnaryOpNode, UnaryOperator, clearAstCache, evaluateFormula, getAstCacheStats, parseFormula, registerDate, registerInfo, registerLogical, registerLookup, registerMath, registerStatistical, registerText, setAstCacheCapacity };
|
|
4788
|
+
export { ArrayValue, BinaryOpNode, BinaryOperator, BlankNode, BooleanNode, CallNode, CellReferenceNode, ErrorNode, FormulaContext, FormulaError, FormulaException, FormulaHelper, FormulaLexer, FormulaNode, FormulaParser, FormulaValue, FunctionCallNode, FunctionRegistry, ImplicitIntersectionNode, LruCache, NamedRangeNode, NumberNode, RangeReferenceNode, RecalcEngine, SheetCellReferenceNode, SheetRangeReferenceNode, SpillReferenceNode, StringNode, TokenType, UnaryOpNode, UnaryOperator, clearAstCache, createWorkbookRecalcModel, evaluateFormula, extractReferences, getAstCacheStats, parseFormula, refContains, registerAggregate, registerArray, registerDate, registerFinance, registerInfo, registerLogical, registerLookup, registerMath, registerMeta, registerStatistical, registerText, setAstCacheCapacity };
|
|
2904
4789
|
//# sourceMappingURL=index.js.map
|
|
2905
4790
|
//# sourceMappingURL=index.js.map
|