@the-w1zard/singularity 1.0.11 → 1.0.13
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/README.html +558 -4
- package/README.md +879 -6
- package/dist/comps/DISRUPTOR_CRYPTO.js +293 -0
- package/dist/comps/binary.js +611 -0
- package/dist/comps/byte_id.js +40 -0
- package/dist/comps/cell-worker.js +120 -0
- package/dist/comps/cell.js +2478 -0
- package/dist/comps/create_live_self.js +22 -0
- package/dist/comps/queue.js +532 -0
- package/dist/comps/vm-types.js +1 -0
- package/dist/db/client/kv_idb.js +590 -0
- package/dist/db/server/bench.js +28 -0
- package/dist/db/server/binary.js +43 -0
- package/dist/db/server/constants.js +8 -0
- package/dist/db/server/crc.js +15 -0
- package/dist/db/server/db.js +1475 -0
- package/dist/db/server/manifest.js +34 -0
- package/dist/db/server/pages.js +100 -0
- package/dist/db/server/storage-worker.js +152 -0
- package/dist/db/server/types.js +14 -0
- package/dist/db/server/wal.js +81 -0
- package/dist/index.js +1 -0
- package/dist/signals.js +18435 -0
- package/dist/y.js +1324 -0
- package/package.json +13 -6
|
@@ -0,0 +1,2478 @@
|
|
|
1
|
+
// CELL
|
|
2
|
+
// #region ══════════════════════════════════════════════════════════════════════════════════════════════════════
|
|
3
|
+
import * as path from 'path';
|
|
4
|
+
import { Registry } from "@the-w1zard/the-registry";
|
|
5
|
+
import * as fs from 'fs';
|
|
6
|
+
import { parse as parseTS } from '@typescript-eslint/typescript-estree';
|
|
7
|
+
const SKIP_KEYS = new Set(['parent', 'loc', 'range', 'tokens', 'comments']);
|
|
8
|
+
export function walkTSNodes(node, visit) {
|
|
9
|
+
if (!node || typeof node !== 'object')
|
|
10
|
+
return;
|
|
11
|
+
if (Array.isArray(node)) {
|
|
12
|
+
for (const n of node)
|
|
13
|
+
walkTSNodes(n, visit);
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
if (typeof node.type === 'string')
|
|
17
|
+
visit(node);
|
|
18
|
+
for (const key of Object.keys(node)) {
|
|
19
|
+
if (SKIP_KEYS.has(key))
|
|
20
|
+
continue;
|
|
21
|
+
walkTSNodes(node[key], visit);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export function parseAST(filePath) {
|
|
25
|
+
const content = fs.readFileSync(filePath, 'utf8');
|
|
26
|
+
const lang = detectLang(filePath);
|
|
27
|
+
if (lang === 'ts' || lang === 'tsx' || lang === 'js' || lang === 'jsx') {
|
|
28
|
+
return parseASTFromContent(content, filePath);
|
|
29
|
+
}
|
|
30
|
+
// css / md / json / jsonc: no parser wired up here, keep the raw text
|
|
31
|
+
return { lang, filePath, raw: content };
|
|
32
|
+
}
|
|
33
|
+
export function boxContains(b, key) {
|
|
34
|
+
const m = KEY_RE.exec(key);
|
|
35
|
+
if (!m || (m[1] ?? undefined) !== b.sheet)
|
|
36
|
+
return false;
|
|
37
|
+
const c = colToIndex(m[2]), r = +m[3];
|
|
38
|
+
return c >= b.c1 && c <= b.c2 && r >= b.r1 && r <= b.r2;
|
|
39
|
+
}
|
|
40
|
+
export function analyzeDependencies(node, cells = new Set(), ranges = []) {
|
|
41
|
+
switch (node.type) {
|
|
42
|
+
case "CellRef":
|
|
43
|
+
cells.add(cellKey(node.col.toUpperCase(), node.row, node.sheet));
|
|
44
|
+
break;
|
|
45
|
+
case "Range": {
|
|
46
|
+
const a = colToIndex(node.start.col.toUpperCase()), b = colToIndex(node.end.col.toUpperCase());
|
|
47
|
+
ranges.push({ sheet: node.sheet, c1: Math.min(a, b), c2: Math.max(a, b), r1: Math.min(node.start.row, node.end.row), r2: Math.max(node.start.row, node.end.row) });
|
|
48
|
+
break;
|
|
49
|
+
}
|
|
50
|
+
case "ColRange": {
|
|
51
|
+
const a = colToIndex(node.start.toUpperCase()), b = colToIndex(node.end.toUpperCase());
|
|
52
|
+
ranges.push({ sheet: node.sheet, c1: Math.min(a, b), c2: Math.max(a, b), r1: 1, r2: MAX_ROW });
|
|
53
|
+
break;
|
|
54
|
+
}
|
|
55
|
+
case "BinOp":
|
|
56
|
+
analyzeDependencies(node.left, cells, ranges);
|
|
57
|
+
analyzeDependencies(node.right, cells, ranges);
|
|
58
|
+
break;
|
|
59
|
+
case "UnaryOp":
|
|
60
|
+
analyzeDependencies(node.operand, cells, ranges);
|
|
61
|
+
break;
|
|
62
|
+
case "FunctionCall":
|
|
63
|
+
for (const arg of node.args)
|
|
64
|
+
analyzeDependencies(arg, cells, ranges);
|
|
65
|
+
break;
|
|
66
|
+
case "ArrayLiteral":
|
|
67
|
+
for (const row of node.rows)
|
|
68
|
+
for (const item of row)
|
|
69
|
+
analyzeDependencies(item, cells, ranges);
|
|
70
|
+
break;
|
|
71
|
+
}
|
|
72
|
+
return { cells, ranges };
|
|
73
|
+
}
|
|
74
|
+
export function directDependents(graph, key) {
|
|
75
|
+
const out = new Set(graph.dependents.get(key) ?? []);
|
|
76
|
+
for (const [target, boxes] of graph.ranges)
|
|
77
|
+
if (boxes.some(b => boxContains(b, key)))
|
|
78
|
+
out.add(target);
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
export function removeDependencies(graph, target) {
|
|
82
|
+
for (const source of graph.deps.get(target) ?? []) {
|
|
83
|
+
const downstream = graph.dependents.get(source);
|
|
84
|
+
if (!downstream)
|
|
85
|
+
continue;
|
|
86
|
+
downstream.delete(target);
|
|
87
|
+
if (downstream.size === 0)
|
|
88
|
+
graph.dependents.delete(source);
|
|
89
|
+
}
|
|
90
|
+
graph.deps.delete(target);
|
|
91
|
+
graph.ranges.delete(target);
|
|
92
|
+
}
|
|
93
|
+
export function registerDependencies(graph, target, dependencies, ranges = []) {
|
|
94
|
+
graph.deps.set(target, dependencies);
|
|
95
|
+
for (const source of dependencies) {
|
|
96
|
+
if (!graph.dependents.has(source))
|
|
97
|
+
graph.dependents.set(source, new Set());
|
|
98
|
+
graph.dependents.get(source).add(target);
|
|
99
|
+
}
|
|
100
|
+
if (ranges.length)
|
|
101
|
+
graph.ranges.set(target, ranges);
|
|
102
|
+
}
|
|
103
|
+
export function collectAffected(graph, changed) {
|
|
104
|
+
const affected = new Set();
|
|
105
|
+
const queue = [changed];
|
|
106
|
+
for (let i = 0; i < queue.length; i++) {
|
|
107
|
+
for (const target of directDependents(graph, queue[i])) {
|
|
108
|
+
if (affected.has(target))
|
|
109
|
+
continue;
|
|
110
|
+
affected.add(target);
|
|
111
|
+
queue.push(target);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return affected;
|
|
115
|
+
}
|
|
116
|
+
export function cloneGraph(graph) {
|
|
117
|
+
const cells = new Map();
|
|
118
|
+
for (const [key, cell] of graph?.cells ?? [])
|
|
119
|
+
cells.set(key, { ...cell });
|
|
120
|
+
const deps = new Map();
|
|
121
|
+
for (const [key, values] of graph?.deps ?? [])
|
|
122
|
+
deps.set(key, new Set(values));
|
|
123
|
+
const dependents = new Map();
|
|
124
|
+
for (const [key, values] of graph?.dependents ?? [])
|
|
125
|
+
dependents.set(key, new Set(values));
|
|
126
|
+
const ranges = new Map();
|
|
127
|
+
for (const [key, boxes] of graph?.ranges ?? [])
|
|
128
|
+
ranges.set(key, boxes.map(b => ({ ...b })));
|
|
129
|
+
return { cells, computed: new Map(graph?.computed ?? []), deps, dependents, ranges };
|
|
130
|
+
}
|
|
131
|
+
function stageCell(graph, key, raw, defaultSheet) {
|
|
132
|
+
removeDependencies(graph, key);
|
|
133
|
+
const cell = { raw };
|
|
134
|
+
if (isFormula(raw)) {
|
|
135
|
+
try {
|
|
136
|
+
const ast = qualifyAst(parseFormula(raw), defaultSheet);
|
|
137
|
+
cell.ast = ast;
|
|
138
|
+
cell.volatile = isVolatileAst(ast);
|
|
139
|
+
const { cells, ranges } = analyzeDependencies(ast);
|
|
140
|
+
registerDependencies(graph, key, cells, ranges);
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
// unparseable: keep raw, no ast, evaluates to #ERROR!
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
graph.cells.set(key, cell);
|
|
147
|
+
}
|
|
148
|
+
export function recalculateDirty(graph, seeds, forced) {
|
|
149
|
+
const seedSet = new Set(seeds);
|
|
150
|
+
const dirty = new Set(seedSet);
|
|
151
|
+
for (const s of seedSet)
|
|
152
|
+
for (const a of collectAffected(graph, s))
|
|
153
|
+
dirty.add(a);
|
|
154
|
+
// edges between dirty cells only; a self-reference is an edge, so it never reaches in-degree 0 and becomes #CYCLE!
|
|
155
|
+
const indegree = new Map();
|
|
156
|
+
for (const k of dirty)
|
|
157
|
+
indegree.set(k, 0);
|
|
158
|
+
const edges = new Map();
|
|
159
|
+
for (const u of dirty) {
|
|
160
|
+
const out = [...directDependents(graph, u)].filter(t => dirty.has(t));
|
|
161
|
+
edges.set(u, out);
|
|
162
|
+
for (const t of out)
|
|
163
|
+
indegree.set(t, indegree.get(t) + 1);
|
|
164
|
+
}
|
|
165
|
+
const queue = [];
|
|
166
|
+
for (const [k, n] of indegree)
|
|
167
|
+
if (n === 0)
|
|
168
|
+
queue.push(k);
|
|
169
|
+
const changed = new Set(forced ?? seedSet);
|
|
170
|
+
const done = new Set();
|
|
171
|
+
for (let i = 0; i < queue.length; i++) {
|
|
172
|
+
const key = queue[i];
|
|
173
|
+
const before = visible(graph, key);
|
|
174
|
+
evaluateCell(graph, key);
|
|
175
|
+
done.add(key);
|
|
176
|
+
if (!sameValue(before, visible(graph, key)))
|
|
177
|
+
changed.add(key);
|
|
178
|
+
for (const t of edges.get(key) ?? []) {
|
|
179
|
+
const left = indegree.get(t) - 1;
|
|
180
|
+
indegree.set(t, left);
|
|
181
|
+
if (left === 0)
|
|
182
|
+
queue.push(t);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
for (const key of dirty) {
|
|
186
|
+
if (done.has(key))
|
|
187
|
+
continue;
|
|
188
|
+
const cell = graph.cells.get(key);
|
|
189
|
+
graph.computed.set(key, "#CYCLE!");
|
|
190
|
+
if (cell)
|
|
191
|
+
cell.computed = "#CYCLE!";
|
|
192
|
+
changed.add(key);
|
|
193
|
+
}
|
|
194
|
+
return changed;
|
|
195
|
+
}
|
|
196
|
+
const splitSections = (fmt) => {
|
|
197
|
+
const out = [];
|
|
198
|
+
let cur = "", q = false;
|
|
199
|
+
for (let i = 0; i < fmt.length; i++) {
|
|
200
|
+
const ch = fmt[i];
|
|
201
|
+
if (ch === "\\" && i + 1 < fmt.length) {
|
|
202
|
+
cur += ch + fmt[++i];
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
if (ch === '"')
|
|
206
|
+
q = !q;
|
|
207
|
+
if (ch === ";" && !q) {
|
|
208
|
+
out.push(cur);
|
|
209
|
+
cur = "";
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
cur += ch;
|
|
213
|
+
}
|
|
214
|
+
return [...out, cur];
|
|
215
|
+
};
|
|
216
|
+
const unquote = (s) => s.replace(/"([^"]*)"/g, "$1").replace(/\\(.)/g, "$1").replace(/_./g, " ").replace(/\*./g, "");
|
|
217
|
+
const bare = (s) => s.replace(/"[^"]*"|\\.|_.|\*./g, "");
|
|
218
|
+
export function formatText(value, fmt) {
|
|
219
|
+
if (typeof value !== "number")
|
|
220
|
+
return toStr(value);
|
|
221
|
+
if (fmt.toLowerCase() === "general")
|
|
222
|
+
return String(value);
|
|
223
|
+
const parts = splitSections(fmt);
|
|
224
|
+
let f = parts[0], v = value, neg = value < 0;
|
|
225
|
+
if (neg && parts.length > 1) {
|
|
226
|
+
f = parts[1];
|
|
227
|
+
v = -value;
|
|
228
|
+
neg = false;
|
|
229
|
+
}
|
|
230
|
+
else if (value === 0 && parts.length > 2)
|
|
231
|
+
f = parts[2];
|
|
232
|
+
const b = bare(f);
|
|
233
|
+
if (b === "@")
|
|
234
|
+
return toStr(value);
|
|
235
|
+
if (/[ymdhs]/i.test(b) && !/[0#?]/.test(b))
|
|
236
|
+
return formatDate(v, f);
|
|
237
|
+
return (neg ? "-" : "") + formatNumber(Math.abs(v), f);
|
|
238
|
+
}
|
|
239
|
+
function fmtPlain(v, pat) {
|
|
240
|
+
let [ip, dp = ""] = pat.split(".");
|
|
241
|
+
const scale = ip.match(/,+$/)?.[0].length ?? 0;
|
|
242
|
+
ip = ip.replace(/,+$/, "");
|
|
243
|
+
const thousands = ip.includes(",");
|
|
244
|
+
ip = ip.replace(/,/g, "");
|
|
245
|
+
const dec = dp.replace(/[^0#?]/g, "").length;
|
|
246
|
+
let [i, d = ""] = round(v / 1000 ** scale, dec).toFixed(dec).split(".");
|
|
247
|
+
const minInt = (ip.match(/0/g) ?? []).length;
|
|
248
|
+
i = i.padStart(minInt, "0");
|
|
249
|
+
if (!minInt && /^0+$/.test(i))
|
|
250
|
+
i = "";
|
|
251
|
+
const minDec = (dp.match(/0/g) ?? []).length;
|
|
252
|
+
while (d.length > minDec && d.endsWith("0"))
|
|
253
|
+
d = d.slice(0, -1);
|
|
254
|
+
if (thousands)
|
|
255
|
+
i = i.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
256
|
+
return d ? `${i}.${d}` : i;
|
|
257
|
+
}
|
|
258
|
+
function formatNumber(v, f) {
|
|
259
|
+
const masked = f.replace(/"[^"]*"|\\./g, s => "\u0001".repeat(s.length));
|
|
260
|
+
v *= 100 ** (masked.match(/%/g) ?? []).length;
|
|
261
|
+
const m = /[0#?][0#?,.]*(?:[Ee][+-]0+)?/.exec(masked);
|
|
262
|
+
if (!m)
|
|
263
|
+
return unquote(f);
|
|
264
|
+
const prefix = unquote(f.slice(0, m.index)), suffix = unquote(f.slice(m.index + m[0].length));
|
|
265
|
+
const sci = /^(.*?)[Ee]([+-])(0+)$/.exec(m[0]);
|
|
266
|
+
if (!sci)
|
|
267
|
+
return prefix + fmtPlain(v, m[0]) + suffix;
|
|
268
|
+
const [, mant, sign, ex] = sci;
|
|
269
|
+
let exp = v === 0 ? 0 : Math.floor(Math.log10(v)), mv = v / 10 ** exp;
|
|
270
|
+
const dec = (mant.split(".")[1] ?? "").replace(/[^0#?]/g, "").length;
|
|
271
|
+
if (round(mv, dec) >= 10) {
|
|
272
|
+
exp++;
|
|
273
|
+
mv /= 10;
|
|
274
|
+
}
|
|
275
|
+
return prefix + fmtPlain(mv, mant) + "E" + (exp < 0 ? "-" : sign === "+" ? "+" : "") + String(Math.abs(exp)).padStart(ex.length, "0") + suffix;
|
|
276
|
+
}
|
|
277
|
+
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
|
|
278
|
+
const DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
|
|
279
|
+
const DT = /^(yyyy|yy|mmmm|mmm|mm|m|dddd|ddd|dd|d|hh|h|ss|s|AM\/PM|A\/P)$/i;
|
|
280
|
+
function formatDate(v, f) {
|
|
281
|
+
const d = fromSerial(v), ampm = /AM\/PM|A\/P/i.test(bare(f)), h12 = d.getHours() % 12 || 12;
|
|
282
|
+
const toks = [];
|
|
283
|
+
f.split(/("[^"]*")/).forEach((seg, i) => {
|
|
284
|
+
if (i % 2) {
|
|
285
|
+
toks.push({ t: seg.slice(1, -1), lit: true });
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
for (const p of seg.split(/(yyyy|yy|mmmm|mmm|mm|m|dddd|ddd|dd|d|hh|h|ss|s|AM\/PM|A\/P)/i))
|
|
289
|
+
if (p)
|
|
290
|
+
toks.push({ t: p, lit: !DT.test(p) });
|
|
291
|
+
});
|
|
292
|
+
return toks.map((tk, i) => {
|
|
293
|
+
if (tk.lit)
|
|
294
|
+
return unquote(tk.t);
|
|
295
|
+
const k = tk.t.toLowerCase();
|
|
296
|
+
if (k === "m" || k === "mm") {
|
|
297
|
+
const prev = toks.slice(0, i).reverse().find(x => !x.lit), next = toks.slice(i + 1).find(x => !x.lit);
|
|
298
|
+
const n = /^h/i.test(prev?.t ?? "") || /^s/i.test(next?.t ?? "") ? d.getMinutes() : d.getMonth() + 1;
|
|
299
|
+
return k === "mm" ? String(n).padStart(2, "0") : String(n);
|
|
300
|
+
}
|
|
301
|
+
switch (k) {
|
|
302
|
+
case "yyyy": return String(d.getFullYear());
|
|
303
|
+
case "yy": return String(d.getFullYear() % 100).padStart(2, "0");
|
|
304
|
+
case "mmmm": return MONTHS[d.getMonth()];
|
|
305
|
+
case "mmm": return MONTHS[d.getMonth()].slice(0, 3);
|
|
306
|
+
case "dddd": return DAYS[d.getDay()];
|
|
307
|
+
case "ddd": return DAYS[d.getDay()].slice(0, 3);
|
|
308
|
+
case "dd": return String(d.getDate()).padStart(2, "0");
|
|
309
|
+
case "d": return String(d.getDate());
|
|
310
|
+
case "hh": return String(ampm ? h12 : d.getHours()).padStart(2, "0");
|
|
311
|
+
case "h": return String(ampm ? h12 : d.getHours());
|
|
312
|
+
case "ss": return String(d.getSeconds()).padStart(2, "0");
|
|
313
|
+
case "s": return String(d.getSeconds());
|
|
314
|
+
case "am/pm": return d.getHours() < 12 ? "AM" : "PM";
|
|
315
|
+
case "a/p": return d.getHours() < 12 ? "A" : "P";
|
|
316
|
+
}
|
|
317
|
+
return tk.t;
|
|
318
|
+
}).join("");
|
|
319
|
+
}
|
|
320
|
+
const EPOCH_UTC = Date.UTC(1899, 11, 30);
|
|
321
|
+
export function dateSerial(d) {
|
|
322
|
+
const days = (Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()) - EPOCH_UTC) / 86400000;
|
|
323
|
+
return days + (d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds() + d.getMilliseconds() / 1000) / 86400;
|
|
324
|
+
}
|
|
325
|
+
export function fromSerial(n) {
|
|
326
|
+
const whole = Math.floor(n), ms = Math.round((n - whole) * 86400000);
|
|
327
|
+
const d = new Date(1899, 11, 30 + whole);
|
|
328
|
+
return new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0, ms);
|
|
329
|
+
}
|
|
330
|
+
const isLeap = (y) => (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;
|
|
331
|
+
function days360(s, e, european) {
|
|
332
|
+
let sd = s.getDate(), ed = e.getDate();
|
|
333
|
+
if (european) {
|
|
334
|
+
if (sd === 31)
|
|
335
|
+
sd = 30;
|
|
336
|
+
if (ed === 31)
|
|
337
|
+
ed = 30;
|
|
338
|
+
}
|
|
339
|
+
else {
|
|
340
|
+
const lastFeb = (d) => d.getMonth() === 1 && d.getDate() === new Date(d.getFullYear(), 2, 0).getDate();
|
|
341
|
+
const sl = lastFeb(s), el = lastFeb(e);
|
|
342
|
+
if (sl && el)
|
|
343
|
+
ed = 30;
|
|
344
|
+
if (sl)
|
|
345
|
+
sd = 30;
|
|
346
|
+
if (ed === 31 && sd >= 30)
|
|
347
|
+
ed = 30;
|
|
348
|
+
if (sd === 31)
|
|
349
|
+
sd = 30;
|
|
350
|
+
}
|
|
351
|
+
return (e.getFullYear() - s.getFullYear()) * 360 + (e.getMonth() - s.getMonth()) * 30 + (ed - sd);
|
|
352
|
+
}
|
|
353
|
+
const newton = (f, x0, tol = 1e-10, max = 100) => {
|
|
354
|
+
let x = x0;
|
|
355
|
+
for (let i = 0; i < max; i++) {
|
|
356
|
+
const y = f(x);
|
|
357
|
+
if (Math.abs(y) < tol)
|
|
358
|
+
return x;
|
|
359
|
+
const h = Math.max(Math.abs(x), 1) * 1e-6;
|
|
360
|
+
const d = (f(x + h) - f(x - h)) / (2 * h);
|
|
361
|
+
const nx = x - y / d;
|
|
362
|
+
if (!Number.isFinite(d) || d === 0 || !Number.isFinite(nx))
|
|
363
|
+
return undefined;
|
|
364
|
+
if (Math.abs(nx - x) < tol)
|
|
365
|
+
return nx;
|
|
366
|
+
x = nx;
|
|
367
|
+
}
|
|
368
|
+
return undefined;
|
|
369
|
+
};
|
|
370
|
+
const sortedNums = (v) => flattenRange(v).filter(x => typeof x === "number").sort((x, y) => x - y);
|
|
371
|
+
const pctInc = (n, p) => {
|
|
372
|
+
if (!n.length || p < 0 || p > 1)
|
|
373
|
+
return "#NUM!";
|
|
374
|
+
const i = p * (n.length - 1), lo = Math.floor(i), hi = Math.ceil(i);
|
|
375
|
+
return n[lo] + (n[hi] - n[lo]) * (i - lo); // old version multiplied the next value instead of the gap
|
|
376
|
+
};
|
|
377
|
+
const VOLATILE_FNS = new Set(["RAND", "RANDBETWEEN", "RANDARRAY", "NOW", "TODAY", "OFFSET", "INDIRECT"]);
|
|
378
|
+
export function isVolatileAst(n) {
|
|
379
|
+
switch (n.type) {
|
|
380
|
+
case "FunctionCall": return VOLATILE_FNS.has(n.name) || n.args.some(isVolatileAst);
|
|
381
|
+
case "BinOp": return isVolatileAst(n.left) || isVolatileAst(n.right);
|
|
382
|
+
case "UnaryOp": return isVolatileAst(n.operand);
|
|
383
|
+
case "ArrayLiteral": return n.rows.some(r => r.some(isVolatileAst));
|
|
384
|
+
default: return false;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
const sameValue = (a, b) => Object.is(a, b) || (Array.isArray(a) && Array.isArray(b) && JSON.stringify(a) === JSON.stringify(b));
|
|
388
|
+
const keyOfBox = (b) => cellKey(indexToCol(b.c1), b.r1, b.sheet);
|
|
389
|
+
const selfBox = (ctx) => {
|
|
390
|
+
if (!ctx.self)
|
|
391
|
+
return undefined;
|
|
392
|
+
const s = parseCellRef(ctx.self), c = colToIndex(s.col);
|
|
393
|
+
return { sheet: s.sheet, c1: c, r1: s.row, c2: c, r2: s.row };
|
|
394
|
+
};
|
|
395
|
+
const refFromText = (text, ctx) => {
|
|
396
|
+
const m = String(text).trim().replace(/\$/g, "").match(/^(?:'?([^'!]+)'?!)?([A-Za-z]+)(\d+)(?::([A-Za-z]+)(\d+))?$/);
|
|
397
|
+
if (!m)
|
|
398
|
+
return undefined;
|
|
399
|
+
const c1 = colToIndex(m[2].toUpperCase()), r1 = +m[3];
|
|
400
|
+
const c2 = m[4] ? colToIndex(m[4].toUpperCase()) : c1, r2 = m[5] ? +m[5] : r1;
|
|
401
|
+
return { sheet: m[1] ?? ctx.sheet, c1: Math.min(c1, c2), r1: Math.min(r1, r2), c2: Math.max(c1, c2), r2: Math.max(r1, r2) };
|
|
402
|
+
};
|
|
403
|
+
const offsetBox = (b, args) => {
|
|
404
|
+
const [dr, dc, h, w] = args.map(x => (x === undefined ? undefined : toNum(x)));
|
|
405
|
+
const height = h ?? b.r2 - b.r1 + 1, width = w ?? b.c2 - b.c1 + 1;
|
|
406
|
+
if (height < 1 || width < 1)
|
|
407
|
+
return undefined;
|
|
408
|
+
const r1 = b.r1 + (dr ?? 0), c1 = b.c1 + (dc ?? 0);
|
|
409
|
+
return { sheet: b.sheet, r1, c1, r2: r1 + height - 1, c2: c1 + width - 1 };
|
|
410
|
+
};
|
|
411
|
+
const refOf = (n, ctx, ev) => {
|
|
412
|
+
if (n.type === "CellRef") {
|
|
413
|
+
const c = colToIndex(n.col.toUpperCase());
|
|
414
|
+
return { sheet: n.sheet ?? ctx.sheet, c1: c, r1: n.row, c2: c, r2: n.row };
|
|
415
|
+
}
|
|
416
|
+
if (n.type === "Range") {
|
|
417
|
+
const a = colToIndex(n.start.col.toUpperCase()), b = colToIndex(n.end.col.toUpperCase());
|
|
418
|
+
return { sheet: n.sheet ?? ctx.sheet, c1: Math.min(a, b), c2: Math.max(a, b), r1: Math.min(n.start.row, n.end.row), r2: Math.max(n.start.row, n.end.row) };
|
|
419
|
+
}
|
|
420
|
+
if (n.type === "FunctionCall" && n.name === "INDIRECT")
|
|
421
|
+
return refFromText(ev(n.args[0]), ctx);
|
|
422
|
+
if (n.type === "FunctionCall" && n.name === "OFFSET") {
|
|
423
|
+
const base = refOf(n.args[0], ctx, ev);
|
|
424
|
+
return base && offsetBox(base, n.args.slice(1).map(x => ev(x)));
|
|
425
|
+
}
|
|
426
|
+
return undefined;
|
|
427
|
+
};
|
|
428
|
+
const boxValue = (b, ctx) => {
|
|
429
|
+
if (b.c1 < 0 || b.r1 < 1)
|
|
430
|
+
return "#REF!";
|
|
431
|
+
const g = expandRange({ sheet: b.sheet, start: { col: indexToCol(b.c1), row: b.r1 }, end: { col: indexToCol(b.c2), row: b.r2 } }, ctx);
|
|
432
|
+
return g.length === 1 && g[0].length === 1 ? g[0][0] : g;
|
|
433
|
+
};
|
|
434
|
+
export const SPECIAL_FORMS = {
|
|
435
|
+
IF: (n, _c, ev) => { const c = ev(n[0]); if (isErr(c))
|
|
436
|
+
return c; return toBool(c) ? ev(n[1]) : n[2] ? ev(n[2]) : false; },
|
|
437
|
+
LAMBDA: (n, ctx) => {
|
|
438
|
+
const params = n.slice(0, -1).map(nameOf);
|
|
439
|
+
if (!n.length || params.some(p => !p))
|
|
440
|
+
return "#VALUE!";
|
|
441
|
+
return { lambda: true, params: params, body: n[n.length - 1], scope: ctx.scope ? new Map(ctx.scope) : undefined };
|
|
442
|
+
},
|
|
443
|
+
LET: (n, ctx, ev) => {
|
|
444
|
+
if (n.length < 3 || n.length % 2 === 0)
|
|
445
|
+
return "#VALUE!";
|
|
446
|
+
const scope = new Map(ctx.scope ?? []), c = { ...ctx, scope };
|
|
447
|
+
for (let i = 0; i < n.length - 1; i += 2) {
|
|
448
|
+
const name = nameOf(n[i]);
|
|
449
|
+
if (!name)
|
|
450
|
+
return "#VALUE!";
|
|
451
|
+
scope.set(name, ev(n[i + 1], c)); // earlier names visible to later ones
|
|
452
|
+
}
|
|
453
|
+
return ev(n[n.length - 1], c);
|
|
454
|
+
},
|
|
455
|
+
INDIRECT: (n, ctx, ev) => { const b = refOf({ type: "FunctionCall", name: "INDIRECT", args: n }, ctx, ev); return b ? boxValue(b, ctx) : "#REF!"; },
|
|
456
|
+
OFFSET: (n, ctx, ev) => { const b = refOf({ type: "FunctionCall", name: "OFFSET", args: n }, ctx, ev); return b ? boxValue(b, ctx) : "#REF!"; },
|
|
457
|
+
ROW: (n, ctx, ev) => {
|
|
458
|
+
const b = n.length ? refOf(n[0], ctx, ev) : selfBox(ctx);
|
|
459
|
+
if (!b)
|
|
460
|
+
return "#VALUE!";
|
|
461
|
+
const h = b.r2 - b.r1 + 1;
|
|
462
|
+
return h === 1 ? b.r1 : Array.from({ length: h }, (_, i) => [b.r1 + i]);
|
|
463
|
+
},
|
|
464
|
+
COLUMN: (n, ctx, ev) => {
|
|
465
|
+
const b = n.length ? refOf(n[0], ctx, ev) : selfBox(ctx);
|
|
466
|
+
if (!b)
|
|
467
|
+
return "#VALUE!";
|
|
468
|
+
const w = b.c2 - b.c1 + 1;
|
|
469
|
+
return w === 1 ? b.c1 + 1 : [Array.from({ length: w }, (_, i) => b.c1 + 1 + i)];
|
|
470
|
+
},
|
|
471
|
+
ANCHORARRAY: (n, ctx, ev) => { const b = refOf(n[0], ctx, ev); if (!b)
|
|
472
|
+
return "#VALUE!"; const v = resolveCell(keyOfBox(b), ctx); return Array.isArray(v) ? v : "#REF!"; },
|
|
473
|
+
ISREF: (n, ctx, ev) => !!refOf(n[0], ctx, ev),
|
|
474
|
+
ISFORMULA: (n, ctx, ev) => { const b = refOf(n[0], ctx, ev); return b ? isFormula(cellAt(ctx, keyOfBox(b))?.raw) : "#VALUE!"; },
|
|
475
|
+
FORMULATEXT: (n, ctx, ev) => {
|
|
476
|
+
const b = refOf(n[0], ctx, ev);
|
|
477
|
+
if (!b)
|
|
478
|
+
return "#VALUE!";
|
|
479
|
+
const raw = cellAt(ctx, keyOfBox(b))?.raw;
|
|
480
|
+
return isFormula(raw) ? raw : "#N/A";
|
|
481
|
+
},
|
|
482
|
+
CELL: (n, ctx, ev) => {
|
|
483
|
+
const kind = String(ev(n[0])).toLowerCase();
|
|
484
|
+
const b = n[1] ? refOf(n[1], ctx, ev) : selfBox(ctx);
|
|
485
|
+
if (!b)
|
|
486
|
+
return "#VALUE!";
|
|
487
|
+
const key = keyOfBox(b);
|
|
488
|
+
switch (kind) {
|
|
489
|
+
case "address": return `$${indexToCol(b.c1)}$${b.r1}`;
|
|
490
|
+
case "row": return b.r1;
|
|
491
|
+
case "col": return b.c1 + 1;
|
|
492
|
+
case "contents": return resolveCell(key, ctx);
|
|
493
|
+
case "filename": return b.sheet ?? "";
|
|
494
|
+
case "type": {
|
|
495
|
+
const v = resolveCell(key, ctx);
|
|
496
|
+
return !cellAt(ctx, key) ? "b" : typeof v === "string" ? "l" : "v";
|
|
497
|
+
}
|
|
498
|
+
default: return "#VALUE!";
|
|
499
|
+
}
|
|
500
|
+
},
|
|
501
|
+
};
|
|
502
|
+
export const isLambda = (v) => typeof v === "object" && v !== null && v.lambda === true;
|
|
503
|
+
export function callLambda(f, args, ctx) {
|
|
504
|
+
if (!isLambda(f))
|
|
505
|
+
return "#VALUE!";
|
|
506
|
+
if (f.native)
|
|
507
|
+
return normalizeResult(f.native(args, ctx));
|
|
508
|
+
if (args.length !== f.params.length)
|
|
509
|
+
return "#VALUE!";
|
|
510
|
+
const scope = new Map(f.scope ?? []);
|
|
511
|
+
f.params.forEach((p, i) => scope.set(p, args[i]));
|
|
512
|
+
return evaluateAst(f.body, { ...ctx, scope });
|
|
513
|
+
}
|
|
514
|
+
const nameOf = (n) => (n.type === "Name" ? n.name.toUpperCase() : undefined);
|
|
515
|
+
const grid = (v) => Array.isArray(v) ? (Array.isArray(v[0]) ? v : [v]) : [[v]];
|
|
516
|
+
const transposeGrid = (m) => m[0]?.map((_, i) => m.map(r => r[i])) ?? [];
|
|
517
|
+
export const lambdaFns = {
|
|
518
|
+
BYROW: (a, ctx) => grid(a[0]).map(row => [callLambda(a[1], [[row]], ctx)]),
|
|
519
|
+
BYCOL: (a, ctx) => {
|
|
520
|
+
const g = grid(a[0]), w = g[0]?.length ?? 0;
|
|
521
|
+
return [Array.from({ length: w }, (_, c) => callLambda(a[1], [g.map(r => [r[c]])], ctx))];
|
|
522
|
+
},
|
|
523
|
+
MAP: (a, ctx) => {
|
|
524
|
+
const f = a[a.length - 1], gs = a.slice(0, -1).map(grid);
|
|
525
|
+
const h = gs[0].length, w = gs[0][0]?.length ?? 0;
|
|
526
|
+
if (gs.some(g => g.length !== h || (g[0]?.length ?? 0) !== w))
|
|
527
|
+
return "#N/A";
|
|
528
|
+
return Array.from({ length: h }, (_, r) => Array.from({ length: w }, (_, c) => callLambda(f, gs.map(g => g[r][c]), ctx)));
|
|
529
|
+
},
|
|
530
|
+
REDUCE: (a, ctx) => {
|
|
531
|
+
let acc = a[0];
|
|
532
|
+
for (const v of flattenRange(a[1])) {
|
|
533
|
+
acc = callLambda(a[2], [acc, v], ctx);
|
|
534
|
+
if (isErr(acc))
|
|
535
|
+
return acc;
|
|
536
|
+
}
|
|
537
|
+
return acc;
|
|
538
|
+
},
|
|
539
|
+
SCAN: (a, ctx) => { let acc = a[0]; return grid(a[1]).map(row => row.map(v => (acc = callLambda(a[2], [acc, v], ctx)))); },
|
|
540
|
+
MAKEARRAY: (a, ctx) => {
|
|
541
|
+
const rows = toNum(a[0]), cols = toNum(a[1]);
|
|
542
|
+
if (rows < 1 || cols < 1)
|
|
543
|
+
return "#VALUE!";
|
|
544
|
+
return Array.from({ length: rows }, (_, r) => Array.from({ length: cols }, (_, c) => callLambda(a[2], [r + 1, c + 1], ctx)));
|
|
545
|
+
},
|
|
546
|
+
WRAPROWS: (a) => { const n = toNum(a[1]); return n < 1 ? "#NUM!" : wrapVec(a); },
|
|
547
|
+
WRAPCOLS: (a) => { const n = toNum(a[1]); return n < 1 ? "#NUM!" : transposeGrid(wrapVec(a)); },
|
|
548
|
+
SINGLE: (a) => scalar(a[0]),
|
|
549
|
+
// needs a spill model, see end
|
|
550
|
+
SEQUENCE: (a) => {
|
|
551
|
+
const rows = toNum(a[0]), cols = toNum(a[1] ?? 1), start = toNum(a[2] ?? 1), step = toNum(a[3] ?? 1);
|
|
552
|
+
return Array.from({ length: rows }, (_, r) => Array.from({ length: cols }, (_, c) => start + step * (r * cols + c)));
|
|
553
|
+
},
|
|
554
|
+
RANDARRAY: (a) => {
|
|
555
|
+
const rows = toNum(a[0] ?? 1), cols = toNum(a[1] ?? 1), min = toNum(a[2] ?? 0), max = toNum(a[3] ?? 1), whole = toBool(a[4]);
|
|
556
|
+
return Array.from({ length: rows }, () => Array.from({ length: cols }, () => whole ? Math.floor(Math.random() * (max - min + 1)) + min : Math.random() * (max - min) + min));
|
|
557
|
+
},
|
|
558
|
+
};
|
|
559
|
+
const wrapVec = (a) => {
|
|
560
|
+
const v = flattenRange(a[0]), n = toNum(a[1]), pad = a[2] ?? "#N/A";
|
|
561
|
+
const out = [];
|
|
562
|
+
for (let i = 0; i < v.length; i += n)
|
|
563
|
+
out.push(Array.from({ length: n }, (_, j) => (i + j < v.length ? v[i + j] : pad)));
|
|
564
|
+
return out;
|
|
565
|
+
};
|
|
566
|
+
export function asNumber(value) {
|
|
567
|
+
if (isSpreadsheetError(value))
|
|
568
|
+
return value;
|
|
569
|
+
if (value === null || value === undefined || value === "") {
|
|
570
|
+
return 0;
|
|
571
|
+
}
|
|
572
|
+
if (typeof value === "number") {
|
|
573
|
+
return Number.isFinite(value)
|
|
574
|
+
? value
|
|
575
|
+
: "#NUM!";
|
|
576
|
+
}
|
|
577
|
+
if (typeof value === "boolean") {
|
|
578
|
+
return value ? 1 : 0;
|
|
579
|
+
}
|
|
580
|
+
if (typeof value === "string") {
|
|
581
|
+
const n = Number(value);
|
|
582
|
+
return Number.isFinite(n)
|
|
583
|
+
? n
|
|
584
|
+
: "#VALUE!";
|
|
585
|
+
}
|
|
586
|
+
return "#VALUE!";
|
|
587
|
+
}
|
|
588
|
+
export function scalar(value) {
|
|
589
|
+
if (!Array.isArray(value))
|
|
590
|
+
return value;
|
|
591
|
+
const flat = flattenRange(value);
|
|
592
|
+
return flat.length > 0
|
|
593
|
+
? flat[0]
|
|
594
|
+
: 0;
|
|
595
|
+
}
|
|
596
|
+
export function compareValues(left, right) {
|
|
597
|
+
if (isSpreadsheetError(left))
|
|
598
|
+
return left;
|
|
599
|
+
if (isSpreadsheetError(right))
|
|
600
|
+
return right;
|
|
601
|
+
const leftNumber = asNumber(left);
|
|
602
|
+
const rightNumber = asNumber(right);
|
|
603
|
+
if (!isSpreadsheetError(leftNumber) &&
|
|
604
|
+
!isSpreadsheetError(rightNumber)) {
|
|
605
|
+
return leftNumber - rightNumber;
|
|
606
|
+
}
|
|
607
|
+
return String(left).localeCompare(String(right));
|
|
608
|
+
}
|
|
609
|
+
export function evaluateBinary(op, left, right) {
|
|
610
|
+
const a = scalar(left);
|
|
611
|
+
const b = scalar(right);
|
|
612
|
+
if (isSpreadsheetError(a))
|
|
613
|
+
return a;
|
|
614
|
+
if (isSpreadsheetError(b))
|
|
615
|
+
return b;
|
|
616
|
+
if (op === "&") {
|
|
617
|
+
return `${a ?? ""}${b ?? ""}`;
|
|
618
|
+
}
|
|
619
|
+
if (op === "=" ||
|
|
620
|
+
op === "==" ||
|
|
621
|
+
op === "<>" ||
|
|
622
|
+
op === "<" ||
|
|
623
|
+
op === "<=" ||
|
|
624
|
+
op === ">" ||
|
|
625
|
+
op === ">=") {
|
|
626
|
+
const comparison = compareValues(a, b);
|
|
627
|
+
if (isSpreadsheetError(comparison))
|
|
628
|
+
return comparison;
|
|
629
|
+
switch (op) {
|
|
630
|
+
case "=":
|
|
631
|
+
case "==":
|
|
632
|
+
return comparison === 0;
|
|
633
|
+
case "<>":
|
|
634
|
+
return comparison !== 0;
|
|
635
|
+
case "<":
|
|
636
|
+
return comparison < 0;
|
|
637
|
+
case "<=":
|
|
638
|
+
return comparison <= 0;
|
|
639
|
+
case ">":
|
|
640
|
+
return comparison > 0;
|
|
641
|
+
case ">=":
|
|
642
|
+
return comparison >= 0;
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
const leftNumber = asNumber(a);
|
|
646
|
+
const rightNumber = asNumber(b);
|
|
647
|
+
if (isSpreadsheetError(leftNumber))
|
|
648
|
+
return leftNumber;
|
|
649
|
+
if (isSpreadsheetError(rightNumber))
|
|
650
|
+
return rightNumber;
|
|
651
|
+
switch (op) {
|
|
652
|
+
case "+":
|
|
653
|
+
return leftNumber + rightNumber;
|
|
654
|
+
case "-":
|
|
655
|
+
return leftNumber - rightNumber;
|
|
656
|
+
case "*":
|
|
657
|
+
return leftNumber * rightNumber;
|
|
658
|
+
case "/":
|
|
659
|
+
return rightNumber === 0
|
|
660
|
+
? "#DIV/0!"
|
|
661
|
+
: leftNumber / rightNumber;
|
|
662
|
+
case "^": {
|
|
663
|
+
const result = leftNumber ** rightNumber;
|
|
664
|
+
return Number.isFinite(result)
|
|
665
|
+
? result
|
|
666
|
+
: "#NUM!";
|
|
667
|
+
}
|
|
668
|
+
default:
|
|
669
|
+
return "#ERROR!";
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
export function evaluateUnary(op, value) {
|
|
673
|
+
const current = scalar(value);
|
|
674
|
+
if (isSpreadsheetError(current))
|
|
675
|
+
return current;
|
|
676
|
+
const number = asNumber(current);
|
|
677
|
+
if (isSpreadsheetError(number))
|
|
678
|
+
return number;
|
|
679
|
+
switch (op) {
|
|
680
|
+
case "-":
|
|
681
|
+
return -number;
|
|
682
|
+
case "%":
|
|
683
|
+
return number / 100;
|
|
684
|
+
default:
|
|
685
|
+
return "#ERROR!";
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
export function recalculateCell(graph, key, visiting = new Set(), completed = new Set()) {
|
|
689
|
+
if (completed.has(key)) {
|
|
690
|
+
return graph.computed.get(key);
|
|
691
|
+
}
|
|
692
|
+
if (visiting.has(key)) {
|
|
693
|
+
const cycle = "#CYCLE!";
|
|
694
|
+
graph.computed.set(key, cycle);
|
|
695
|
+
const cell = graph.cells.get(key);
|
|
696
|
+
if (cell)
|
|
697
|
+
cell.computed = cycle;
|
|
698
|
+
return cycle;
|
|
699
|
+
}
|
|
700
|
+
const cell = graph.cells.get(key);
|
|
701
|
+
if (!cell) {
|
|
702
|
+
return 0;
|
|
703
|
+
}
|
|
704
|
+
if (!isFormula(cell.raw)) {
|
|
705
|
+
graph.computed.delete(key);
|
|
706
|
+
completed.add(key);
|
|
707
|
+
return cell.raw ?? 0;
|
|
708
|
+
}
|
|
709
|
+
visiting.add(key);
|
|
710
|
+
const dependencies = graph.deps.get(key) ?? new Set();
|
|
711
|
+
for (const dependency of dependencies) {
|
|
712
|
+
const dependencyCell = graph.cells.get(dependency);
|
|
713
|
+
if (dependencyCell && isFormula(dependencyCell.raw)) {
|
|
714
|
+
recalculateCell(graph, dependency, visiting, completed);
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
let result;
|
|
718
|
+
try {
|
|
719
|
+
result = evaluateSpreadsheetAst(cell.ast ?? parseFormula(cell.raw), graph);
|
|
720
|
+
}
|
|
721
|
+
catch {
|
|
722
|
+
result = "#ERROR!";
|
|
723
|
+
}
|
|
724
|
+
cell.ast ??= parseFormula(cell.raw);
|
|
725
|
+
cell.computed = result;
|
|
726
|
+
graph.computed.set(key, result);
|
|
727
|
+
visiting.delete(key);
|
|
728
|
+
completed.add(key);
|
|
729
|
+
return result;
|
|
730
|
+
}
|
|
731
|
+
export function recalculateAffected(graph, changed) {
|
|
732
|
+
const affected = collectAffected(graph, changed);
|
|
733
|
+
const completed = new Set();
|
|
734
|
+
for (const key of affected) {
|
|
735
|
+
recalculateCell(graph, key, new Set(), completed);
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
export function createEvalContext(graph) {
|
|
739
|
+
return {
|
|
740
|
+
store: graph.cells,
|
|
741
|
+
computed: graph.computed
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
export function isFormula(value) {
|
|
745
|
+
return typeof value === "string" && value.startsWith("=");
|
|
746
|
+
}
|
|
747
|
+
export function normalizeCellRef(input, defaultSheet) {
|
|
748
|
+
const match = input.match(/^(?:(.+)!)?([A-Za-z]+)(\d+)$/);
|
|
749
|
+
if (!match) {
|
|
750
|
+
throw new Error(`[useSpreadsheet] Invalid cell reference "${input}". Expected A1 or Sheet!A1.`);
|
|
751
|
+
}
|
|
752
|
+
const sheet = match[1] ?? defaultSheet;
|
|
753
|
+
const col = match[2].toUpperCase();
|
|
754
|
+
const row = Number(match[3]);
|
|
755
|
+
return cellKey(col, row, sheet);
|
|
756
|
+
}
|
|
757
|
+
export function parseCellRef(input, defaultSheet) {
|
|
758
|
+
const normalized = normalizeCellRef(input, defaultSheet);
|
|
759
|
+
const match = normalized.match(/^(?:(.+)!)?([A-Z]+)(\d+)$/);
|
|
760
|
+
return {
|
|
761
|
+
sheet: match[1],
|
|
762
|
+
col: match[2],
|
|
763
|
+
row: Number(match[3])
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
export function createSpreadsheetGraph(initial) {
|
|
767
|
+
return cloneGraph(initial);
|
|
768
|
+
}
|
|
769
|
+
const numbersOrError = (v) => {
|
|
770
|
+
const out = [];
|
|
771
|
+
for (const x of flattenRange(v)) {
|
|
772
|
+
const e = errCode(x);
|
|
773
|
+
if (e)
|
|
774
|
+
return e;
|
|
775
|
+
if (typeof x === "number")
|
|
776
|
+
out.push(x);
|
|
777
|
+
}
|
|
778
|
+
return out;
|
|
779
|
+
};
|
|
780
|
+
export const math = {
|
|
781
|
+
SUM: (a) => { const n = numbersOrError(a); return typeof n === "string" ? n : n.reduce((s, v) => s + v, 0); },
|
|
782
|
+
SUMIF: (a, ctx) => {
|
|
783
|
+
const range = flattenRange(a[0]);
|
|
784
|
+
const crit = a[1];
|
|
785
|
+
const sumRange = a[2] !== undefined ? flattenRange(a[2]) : range;
|
|
786
|
+
return range.reduce((s, v, i) => s + (matchCriteria(v, crit) ? toNum(sumRange[i] ?? 0) : 0), 0);
|
|
787
|
+
},
|
|
788
|
+
SUMIFS: (a) => {
|
|
789
|
+
const sumRange = flattenRange(a[0]);
|
|
790
|
+
let result = 0;
|
|
791
|
+
for (let i = 0; i < sumRange.length; i++) {
|
|
792
|
+
let match = true;
|
|
793
|
+
for (let p = 1; p < a.length - 1; p += 2) {
|
|
794
|
+
const cr = flattenRange(a[p]);
|
|
795
|
+
if (!matchCriteria(cr[i], a[p + 1])) {
|
|
796
|
+
match = false;
|
|
797
|
+
break;
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
if (match)
|
|
801
|
+
result += toNum(sumRange[i]);
|
|
802
|
+
}
|
|
803
|
+
return result;
|
|
804
|
+
},
|
|
805
|
+
PRODUCT: (a) => { const n = numbersOrError(a); return typeof n === "string" ? n : n.length ? n.reduce((p, v) => p * v, 1) : 0; },
|
|
806
|
+
AVERAGE: (a) => { const n = numbersOrError(a); return typeof n === "string" ? n : n.length ? n.reduce((s, v) => s + v, 0) / n.length : "#DIV/0!"; },
|
|
807
|
+
AVERAGEIF: (a) => {
|
|
808
|
+
const range = flattenRange(a[0]);
|
|
809
|
+
const crit = a[1];
|
|
810
|
+
const avgRange = a[2] !== undefined ? flattenRange(a[2]) : range;
|
|
811
|
+
const nums = range.reduce((acc, v, i) => { if (matchCriteria(v, crit))
|
|
812
|
+
acc.push(toNum(avgRange[i] ?? 0)); return acc; }, []);
|
|
813
|
+
return nums.length ? nums.reduce((s, v) => s + v, 0) / nums.length : { error: '#DIV/0!' };
|
|
814
|
+
},
|
|
815
|
+
COUNT: (a) => flattenRange(a).filter(v => typeof v === "number").length,
|
|
816
|
+
COUNTA: (a) => flattenRange(a).filter(v => v !== null && v !== undefined && v !== '').length,
|
|
817
|
+
COUNTBLANK: (a) => flattenRange(a).filter(v => v === null || v === undefined || v === '').length,
|
|
818
|
+
COUNTIF: (a) => flattenRange(a[0]).filter(v => matchCriteria(v, a[1])).length,
|
|
819
|
+
COUNTIFS: (a) => {
|
|
820
|
+
const ranges = [];
|
|
821
|
+
const crits = [];
|
|
822
|
+
for (let i = 0; i < a.length; i += 2) {
|
|
823
|
+
ranges.push(flattenRange(a[i]));
|
|
824
|
+
crits.push(a[i + 1]);
|
|
825
|
+
}
|
|
826
|
+
const len = ranges[0]?.length ?? 0;
|
|
827
|
+
let count = 0;
|
|
828
|
+
for (let i = 0; i < len; i++)
|
|
829
|
+
if (ranges.every((r, ri) => matchCriteria(r[i], crits[ri])))
|
|
830
|
+
count++;
|
|
831
|
+
return count;
|
|
832
|
+
},
|
|
833
|
+
MIN: (a) => { const n = numbersOrError(a); return typeof n === "string" ? n : n.length ? n.reduce((m, v) => (v < m ? v : m)) : 0; },
|
|
834
|
+
MAX: (a) => { const n = numbersOrError(a); return typeof n === "string" ? n : n.length ? n.reduce((m, v) => (v > m ? v : m)) : 0; },
|
|
835
|
+
MINA: (a) => { const n = flattenRange(a).map(toNum); return n.length ? Math.min(...n) : 0; },
|
|
836
|
+
MAXA: (a) => { const n = flattenRange(a).map(toNum); return n.length ? Math.max(...n) : 0; },
|
|
837
|
+
SMALL: (a) => { const n = flattenRange(a[0]).map(toNum).sort((x, y) => x - y); return n[toNum(a[1]) - 1] ?? { error: '#NUM!' }; },
|
|
838
|
+
LARGE: (a) => { const n = flattenRange(a[0]).map(toNum).sort((x, y) => y - x); return n[toNum(a[1]) - 1] ?? { error: '#NUM!' }; },
|
|
839
|
+
ABS: (a) => Math.abs(toNum(a[0])),
|
|
840
|
+
SIGN: (a) => Math.sign(toNum(a[0])),
|
|
841
|
+
SQRT: (a) => { const v = toNum(a[0]); return v < 0 ? { error: '#NUM!' } : Math.sqrt(v); },
|
|
842
|
+
SQRTPI: (a) => Math.sqrt(Math.PI * toNum(a[0])),
|
|
843
|
+
PI: () => Math.PI,
|
|
844
|
+
EXP: (a) => Math.exp(toNum(a[0])),
|
|
845
|
+
LN: (a) => Math.log(toNum(a[0])),
|
|
846
|
+
LOG: (a) => Math.log(toNum(a[0])) / Math.log(toNum(a[1] ?? 10)),
|
|
847
|
+
LOG10: (a) => Math.log10(toNum(a[0])),
|
|
848
|
+
POWER: (a) => Math.pow(toNum(a[0]), toNum(a[1])),
|
|
849
|
+
MOD: (a) => { const d = toNum(a[1]); return d === 0 ? { error: '#DIV/0!' } : toNum(a[0]) % d; },
|
|
850
|
+
QUOTIENT: (a) => { const d = toNum(a[1]); return d === 0 ? { error: '#DIV/0!' } : Math.trunc(toNum(a[0]) / d); },
|
|
851
|
+
INT: (a) => Math.floor(toNum(a[0])),
|
|
852
|
+
TRUNC: (a) => Math.trunc(toNum(a[0])),
|
|
853
|
+
ROUND: (a) => round(toNum(a[0]), toNum(a[1] ?? 0)),
|
|
854
|
+
ROUNDUP: (a) => { const f = Math.pow(10, toNum(a[1] ?? 0)); return Math.ceil(toNum(a[0]) * f) / f; },
|
|
855
|
+
ROUNDDOWN: (a) => { const f = Math.pow(10, toNum(a[1] ?? 0)); return Math.floor(toNum(a[0]) * f) / f; },
|
|
856
|
+
MROUND: (a) => { const m = toNum(a[1]); return m === 0 ? 0 : Math.round(toNum(a[0]) / m) * m; },
|
|
857
|
+
CEILING: (a) => { const m = toNum(a[1] ?? 1); return m === 0 ? 0 : Math.ceil(toNum(a[0]) / m) * m; },
|
|
858
|
+
FLOOR: (a) => { const m = toNum(a[1] ?? 1); return m === 0 ? 0 : Math.floor(toNum(a[0]) / m) * m; },
|
|
859
|
+
EVEN: (a) => { const v = Math.ceil(Math.abs(toNum(a[0]))); return (v % 2 === 0 ? v : v + 1) * (toNum(a[0]) < 0 ? -1 : 1); },
|
|
860
|
+
ODD: (a) => { const v = Math.ceil(Math.abs(toNum(a[0]))); return (v % 2 !== 0 ? v : v + 1) * (toNum(a[0]) < 0 ? -1 : 1); },
|
|
861
|
+
RAND: () => Math.random(),
|
|
862
|
+
RANDBETWEEN: (a) => Math.floor(Math.random() * (toNum(a[1]) - toNum(a[0]) + 1)) + toNum(a[0]),
|
|
863
|
+
FACT: (a) => { let n = toNum(a[0]); let r = 1; while (n > 1)
|
|
864
|
+
r *= n--; return r; },
|
|
865
|
+
COMBIN: (a) => combin(toNum(a[0]), toNum(a[1])),
|
|
866
|
+
PERMUT: (a) => { let n = toNum(a[0]), k = toNum(a[1]), r = 1; for (let i = 0; i < k; i++)
|
|
867
|
+
r *= (n - i); return r; },
|
|
868
|
+
GCD: (a) => flattenRange(a).map(toNum).reduce((g, v) => gcd(Math.abs(g), Math.abs(v))),
|
|
869
|
+
LCM: (a) => flattenRange(a).map(toNum).reduce((l, v) => Math.abs(l * v) / gcd(Math.abs(l), Math.abs(v))),
|
|
870
|
+
SIN: (a) => Math.sin(toNum(a[0])), COS: (a) => Math.cos(toNum(a[0])), TAN: (a) => Math.tan(toNum(a[0])),
|
|
871
|
+
ASIN: (a) => Math.asin(toNum(a[0])), ACOS: (a) => Math.acos(toNum(a[0])), ATAN: (a) => Math.atan(toNum(a[0])),
|
|
872
|
+
ATAN2: (a) => Math.atan2(toNum(a[0]), toNum(a[1])),
|
|
873
|
+
SINH: (a) => Math.sinh(toNum(a[0])), COSH: (a) => Math.cosh(toNum(a[0])), TANH: (a) => Math.tanh(toNum(a[0])),
|
|
874
|
+
DEGREES: (a) => toNum(a[0]) * 180 / Math.PI,
|
|
875
|
+
RADIANS: (a) => toNum(a[0]) * Math.PI / 180,
|
|
876
|
+
ROMAN: (a) => toRoman(toNum(a[0])),
|
|
877
|
+
SUMPRODUCT: (a) => {
|
|
878
|
+
const ranges = a.map(x => flattenRange(x).map(toNum));
|
|
879
|
+
const len = ranges[0]?.length ?? 0;
|
|
880
|
+
let s = 0;
|
|
881
|
+
for (let i = 0; i < len; i++)
|
|
882
|
+
s += ranges.reduce((p, r) => p * r[i], 1);
|
|
883
|
+
return s;
|
|
884
|
+
},
|
|
885
|
+
MMULT: (a) => {
|
|
886
|
+
const A = a[0], B = a[1];
|
|
887
|
+
if (!Array.isArray(A) || !Array.isArray(B))
|
|
888
|
+
return { error: '#VALUE!' };
|
|
889
|
+
return A.map(row => B[0].map((_, j) => row.reduce((s, _, k) => s + row[k] * B[k][j], 0)));
|
|
890
|
+
},
|
|
891
|
+
TRANSPOSE: (a) => {
|
|
892
|
+
const m = a[0];
|
|
893
|
+
if (!Array.isArray(m))
|
|
894
|
+
return [[a[0]]];
|
|
895
|
+
return m[0].map((_, i) => m.map(r => r[i]));
|
|
896
|
+
},
|
|
897
|
+
};
|
|
898
|
+
export const text = {
|
|
899
|
+
LEN: (a) => toStr(a[0]).length,
|
|
900
|
+
LEFT: (a) => toStr(a[0]).slice(0, toNum(a[1] ?? 1)),
|
|
901
|
+
RIGHT: (a) => { const s = toStr(a[0]); return s.slice(s.length - toNum(a[1] ?? 1)); },
|
|
902
|
+
MID: (a) => toStr(a[0]).slice(toNum(a[1]) - 1, toNum(a[1]) - 1 + toNum(a[2])),
|
|
903
|
+
UPPER: (a) => toStr(a[0]).toUpperCase(),
|
|
904
|
+
LOWER: (a) => toStr(a[0]).toLowerCase(),
|
|
905
|
+
PROPER: (a) => toStr(a[0]).replace(/\b\w/g, c => c.toUpperCase()),
|
|
906
|
+
TRIM: (a) => toStr(a[0]).trim().replace(/\s+/g, ' '),
|
|
907
|
+
CLEAN: (a) => toStr(a[0]).replace(/[\x00-\x1F]/g, ''),
|
|
908
|
+
CONCATENATE: (a) => flattenRange(a).map(toStr).join(''),
|
|
909
|
+
CONCAT: (a) => flattenRange(a).map(toStr).join(''),
|
|
910
|
+
TEXTJOIN: (a) => {
|
|
911
|
+
const delim = toStr(a[0]);
|
|
912
|
+
const ignoreEmpty = toBool(a[1]);
|
|
913
|
+
const vals = flattenRange(a.slice(2)).map(toStr);
|
|
914
|
+
return (ignoreEmpty ? vals.filter(v => v !== '') : vals).join(delim);
|
|
915
|
+
},
|
|
916
|
+
FIND: (a) => { const i = toStr(a[1]).indexOf(toStr(a[0]), toNum(a[2] ?? 1) - 1); return i === -1 ? { error: '#VALUE!' } : i + 1; },
|
|
917
|
+
SEARCH: (a) => {
|
|
918
|
+
const hay = toStr(a[1]).toLowerCase();
|
|
919
|
+
const needle = toStr(a[0]).toLowerCase().replace(/[*?]/g, m => m === '*' ? '.*' : '.');
|
|
920
|
+
const re = new RegExp(needle);
|
|
921
|
+
const m = hay.slice(toNum(a[2] ?? 1) - 1).search(re);
|
|
922
|
+
return m === -1 ? { error: '#VALUE!' } : m + toNum(a[2] ?? 1);
|
|
923
|
+
},
|
|
924
|
+
SUBSTITUTE: (a) => {
|
|
925
|
+
const src = toStr(a[0]), from = toStr(a[1]), to = toStr(a[2]);
|
|
926
|
+
if (a[3] !== undefined) {
|
|
927
|
+
let n = 0, i = -1, result = src;
|
|
928
|
+
const nth = toNum(a[3]);
|
|
929
|
+
while ((i = result.indexOf(from, i + 1)) !== -1) {
|
|
930
|
+
n++;
|
|
931
|
+
if (n === nth)
|
|
932
|
+
return result.slice(0, i) + to + result.slice(i + from.length);
|
|
933
|
+
}
|
|
934
|
+
return src;
|
|
935
|
+
}
|
|
936
|
+
return src.split(from).join(to);
|
|
937
|
+
},
|
|
938
|
+
REPLACE: (a) => { const s = toStr(a[0]); return s.slice(0, toNum(a[1]) - 1) + toStr(a[3]) + s.slice(toNum(a[1]) - 1 + toNum(a[2])); },
|
|
939
|
+
REPT: (a) => toStr(a[0]).repeat(Math.max(0, toNum(a[1]))),
|
|
940
|
+
CHAR: (a) => String.fromCharCode(toNum(a[0])),
|
|
941
|
+
CODE: (a) => toStr(a[0]).charCodeAt(0),
|
|
942
|
+
EXACT: (a) => toStr(a[0]) === toStr(a[1]),
|
|
943
|
+
TEXT: (a) => formatText(toNum(a[0]), toStr(a[1])),
|
|
944
|
+
VALUE: (a) => { const n = parseFloat(toStr(a[0]).replace(/[,$%]/g, '')); return isNaN(n) ? { error: '#VALUE!' } : n; },
|
|
945
|
+
FIXED: (a) => toNum(a[0]).toFixed(toNum(a[1] ?? 2)),
|
|
946
|
+
DOLLAR: (a) => '$' + toNum(a[0]).toFixed(toNum(a[1] ?? 2)),
|
|
947
|
+
NUMBERVALUE: (a) => parseFloat(toStr(a[0]).replace(toStr(a[2] ?? ','), '').replace(toStr(a[1] ?? '.'), '.')),
|
|
948
|
+
UNICHAR: (a) => String.fromCodePoint(toNum(a[0])),
|
|
949
|
+
UNICODE: (a) => toStr(a[0]).codePointAt(0) ?? 0,
|
|
950
|
+
ASC: (a) => toStr(a[0]),
|
|
951
|
+
BAHTTEXT: (a) => String(a[0]),
|
|
952
|
+
PHONETIC: (a) => toStr(a[0]),
|
|
953
|
+
ARRAYTOTEXT: (a) => flattenRange(a[0]).map(toStr).join(toNum(a[1] ?? 0) === 1 ? ', ' : ','),
|
|
954
|
+
VALUETOTEXT: (a) => typeof a[0] === 'string' ? (toNum(a[1] ?? 0) === 1 ? `"${a[0]}"` : toStr(a[0])) : toStr(a[0]),
|
|
955
|
+
};
|
|
956
|
+
export const logical = {
|
|
957
|
+
IF: (a) => toBool(a[0]) ? a[1] : (a[2] !== undefined ? a[2] : false),
|
|
958
|
+
IFS: (a) => {
|
|
959
|
+
for (let i = 0; i < a.length - 1; i += 2)
|
|
960
|
+
if (toBool(a[i]))
|
|
961
|
+
return a[i + 1];
|
|
962
|
+
return { error: '#N/A' };
|
|
963
|
+
},
|
|
964
|
+
AND: (a) => flattenRange(a).every(toBool),
|
|
965
|
+
OR: (a) => flattenRange(a).some(toBool),
|
|
966
|
+
NOT: (a) => !toBool(a[0]),
|
|
967
|
+
XOR: (a) => flattenRange(a).filter(toBool).length % 2 !== 0,
|
|
968
|
+
TRUE: () => true,
|
|
969
|
+
FALSE: () => false,
|
|
970
|
+
SWITCH: (a) => {
|
|
971
|
+
const expr = a[0];
|
|
972
|
+
for (let i = 1; i < a.length - 1; i += 2)
|
|
973
|
+
if (looseEqual(expr, a[i]))
|
|
974
|
+
return a[i + 1];
|
|
975
|
+
return a.length % 2 === 0 ? a[a.length - 1] : { error: '#N/A' };
|
|
976
|
+
},
|
|
977
|
+
IFERROR: (a) => isErr(a[0]) ? a[1] : a[0],
|
|
978
|
+
IFNA: (a) => errCode(a[0]) === "#N/A" ? a[1] : a[0],
|
|
979
|
+
ISBLANK: (a) => a[0] === null || a[0] === undefined || a[0] === '',
|
|
980
|
+
ISERROR: (a) => isErr(a[0]),
|
|
981
|
+
ISERR: (a) => isErr(a[0]) && errCode(a[0]) !== "#N/A",
|
|
982
|
+
ISNA: (a) => errCode(a[0]) === "#N/A",
|
|
983
|
+
"ERROR.TYPE": (a) => {
|
|
984
|
+
const map = { "#NULL!": 1, "#DIV/0!": 2, "#VALUE!": 3, "#REF!": 4, "#NAME?": 5, "#NUM!": 6, "#N/A": 7 };
|
|
985
|
+
return map[errCode(a[0]) ?? ""] ?? "#N/A";
|
|
986
|
+
},
|
|
987
|
+
ISLOGICAL: (a) => typeof a[0] === 'boolean',
|
|
988
|
+
ISNUMBER: (a) => typeof a[0] === 'number',
|
|
989
|
+
ISTEXT: (a) => typeof a[0] === 'string',
|
|
990
|
+
ISNONTEXT: (a) => typeof a[0] !== 'string',
|
|
991
|
+
ISEVEN: (a) => toNum(a[0]) % 2 === 0,
|
|
992
|
+
ISODD: (a) => toNum(a[0]) % 2 !== 0,
|
|
993
|
+
N: (a) => typeof a[0] === 'number' ? a[0] : typeof a[0] === 'boolean' ? (a[0] ? 1 : 0) : 0,
|
|
994
|
+
NA: () => ({ error: '#N/A' }),
|
|
995
|
+
TYPE: (a) => { if (typeof a[0] === 'number')
|
|
996
|
+
return 1; if (typeof a[0] === 'string')
|
|
997
|
+
return 2; if (typeof a[0] === 'boolean')
|
|
998
|
+
return 4; if (isErr(a[0]))
|
|
999
|
+
return 16; if (Array.isArray(a[0]))
|
|
1000
|
+
return 64; return 0; },
|
|
1001
|
+
};
|
|
1002
|
+
export const lookup = {
|
|
1003
|
+
VLOOKUP: (a) => {
|
|
1004
|
+
const val = a[0], data = a[1], colIdx = toNum(a[2]) - 1, approx = a[3] !== false && a[3] !== 0;
|
|
1005
|
+
if (!Array.isArray(data))
|
|
1006
|
+
return { error: '#VALUE!' };
|
|
1007
|
+
const col0 = data.map(r => r[0]);
|
|
1008
|
+
const i = approx ? approxMatch(val, col0) : col0.findIndex(v => looseEqual(v, val));
|
|
1009
|
+
return i === -1 ? { error: '#N/A' } : (data[i]?.[colIdx] ?? { error: '#REF!' });
|
|
1010
|
+
},
|
|
1011
|
+
HLOOKUP: (a) => {
|
|
1012
|
+
const val = a[0], data = a[1], rowIdx = toNum(a[2]) - 1, approx = a[3] !== false && a[3] !== 0;
|
|
1013
|
+
if (!Array.isArray(data))
|
|
1014
|
+
return { error: '#VALUE!' };
|
|
1015
|
+
const row0 = data[0] ?? [];
|
|
1016
|
+
const i = approx ? approxMatch(val, row0) : row0.findIndex(v => looseEqual(v, val));
|
|
1017
|
+
return i === -1 ? { error: '#N/A' } : (data[rowIdx]?.[i] ?? { error: '#REF!' });
|
|
1018
|
+
},
|
|
1019
|
+
XLOOKUP: (a) => {
|
|
1020
|
+
const val = a[0], look = flattenRange(a[1]), ret = flattenRange(a[2]);
|
|
1021
|
+
const notFound = a[3] === undefined ? "#N/A" : a[3];
|
|
1022
|
+
const mode = toNum(a[4] ?? 0), search = toNum(a[5] ?? 1);
|
|
1023
|
+
const order = [...look.keys()];
|
|
1024
|
+
if (search < 0)
|
|
1025
|
+
order.reverse();
|
|
1026
|
+
const i = findMatch(val, look, order, mode);
|
|
1027
|
+
return i === -1 ? notFound : (ret[i] ?? "#N/A");
|
|
1028
|
+
},
|
|
1029
|
+
INDEX: (a) => {
|
|
1030
|
+
const data = a[0];
|
|
1031
|
+
if (!Array.isArray(data))
|
|
1032
|
+
return data;
|
|
1033
|
+
const r = toNum(a[1]), c = toNum(a[2] ?? 1);
|
|
1034
|
+
if (r === 0)
|
|
1035
|
+
return data.map(row => row[c - 1]);
|
|
1036
|
+
if (c === 0)
|
|
1037
|
+
return data[r - 1];
|
|
1038
|
+
return data[r - 1]?.[c - 1] ?? { error: '#REF!' };
|
|
1039
|
+
},
|
|
1040
|
+
MATCH: (a) => {
|
|
1041
|
+
const val = a[0], arr = flattenRange(a[1]), mode = toNum(a[2] ?? 1);
|
|
1042
|
+
let i = -1;
|
|
1043
|
+
if (mode === 0)
|
|
1044
|
+
i = findMatch(val, arr, [...arr.keys()], typeof val === "string" ? 2 : 0);
|
|
1045
|
+
else if (mode > 0)
|
|
1046
|
+
i = approxMatch(val, arr);
|
|
1047
|
+
else {
|
|
1048
|
+
for (let j = 0; j < arr.length; j++) {
|
|
1049
|
+
if (compare(arr[j], val) >= 0)
|
|
1050
|
+
i = j;
|
|
1051
|
+
else
|
|
1052
|
+
break;
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
return i === -1 ? "#N/A" : i + 1;
|
|
1056
|
+
},
|
|
1057
|
+
LOOKUP: (a) => {
|
|
1058
|
+
const val = a[0], lookArr = flattenRange(a[1]), retArr = a[2] !== undefined ? flattenRange(a[2]) : lookArr;
|
|
1059
|
+
const i = approxMatch(val, lookArr);
|
|
1060
|
+
return i === -1 ? { error: '#N/A' } : retArr[i];
|
|
1061
|
+
},
|
|
1062
|
+
CHOOSE: (a) => { const i = toNum(a[0]); return a[i] ?? { error: '#VALUE!' }; },
|
|
1063
|
+
COLUMNS: (a) => Array.isArray(a[0]) ? (a[0][0]?.length ?? 1) : 1,
|
|
1064
|
+
SORT: (a) => {
|
|
1065
|
+
const data = a[0];
|
|
1066
|
+
if (!Array.isArray(data))
|
|
1067
|
+
return [[a[0]]];
|
|
1068
|
+
const col = toNum(a[1] ?? 1) - 1;
|
|
1069
|
+
const dir = toNum(a[2] ?? 1);
|
|
1070
|
+
return [...data].sort((x, y) => {
|
|
1071
|
+
const vx = Array.isArray(x) ? x[col] : x;
|
|
1072
|
+
const vy = Array.isArray(y) ? y[col] : y;
|
|
1073
|
+
return dir * compare(vx, vy);
|
|
1074
|
+
});
|
|
1075
|
+
},
|
|
1076
|
+
SORTBY: (a) => {
|
|
1077
|
+
const data = a[0];
|
|
1078
|
+
if (!Array.isArray(data))
|
|
1079
|
+
return [[a[0]]];
|
|
1080
|
+
const keys = [];
|
|
1081
|
+
for (let i = 1; i < a.length; i += 2)
|
|
1082
|
+
keys.push([flattenRange(a[i]), toNum(a[i + 1] ?? 1)]);
|
|
1083
|
+
return [...data].sort((x, y) => {
|
|
1084
|
+
const ix = data.indexOf(x);
|
|
1085
|
+
const iy = data.indexOf(y);
|
|
1086
|
+
for (const [arr, dir] of keys) {
|
|
1087
|
+
const c = dir * compare(arr[ix], arr[iy]);
|
|
1088
|
+
if (c !== 0)
|
|
1089
|
+
return c;
|
|
1090
|
+
}
|
|
1091
|
+
return 0;
|
|
1092
|
+
});
|
|
1093
|
+
},
|
|
1094
|
+
FILTER: (a) => {
|
|
1095
|
+
const data = a[0];
|
|
1096
|
+
const mask = flattenRange(a[1]);
|
|
1097
|
+
if (!Array.isArray(data))
|
|
1098
|
+
return a[2] ?? { error: '#CALC!' };
|
|
1099
|
+
const out = data.filter((_, i) => toBool(mask[i]));
|
|
1100
|
+
return out.length ? out : (a[2] ?? { error: '#CALC!' });
|
|
1101
|
+
},
|
|
1102
|
+
UNIQUE: (a) => {
|
|
1103
|
+
const data = a[0];
|
|
1104
|
+
if (!Array.isArray(data))
|
|
1105
|
+
return [[a[0]]];
|
|
1106
|
+
const seen = new Set();
|
|
1107
|
+
return data.filter(r => { const k = JSON.stringify(r); if (seen.has(k))
|
|
1108
|
+
return false; seen.add(k); return true; });
|
|
1109
|
+
},
|
|
1110
|
+
XMATCH: (a) => {
|
|
1111
|
+
const arr = flattenRange(a[1]), mode = toNum(a[2] ?? 0), search = toNum(a[3] ?? 1);
|
|
1112
|
+
const order = [...arr.keys()];
|
|
1113
|
+
if (search < 0)
|
|
1114
|
+
order.reverse();
|
|
1115
|
+
const i = findMatch(a[0], arr, order, mode);
|
|
1116
|
+
return i === -1 ? "#N/A" : i + 1;
|
|
1117
|
+
},
|
|
1118
|
+
HYPERLINK: (a) => a[1] ?? a[0],
|
|
1119
|
+
GETPIVOTDATA: () => ({ error: '#REF!' }),
|
|
1120
|
+
};
|
|
1121
|
+
export const dateTime = {
|
|
1122
|
+
TODAY: () => Math.floor(dateSerial(new Date())),
|
|
1123
|
+
NOW: () => dateSerial(new Date()),
|
|
1124
|
+
DATE: (a) => Math.floor(dateSerial(new Date(toNum(a[0]), toNum(a[1]) - 1, toNum(a[2])))),
|
|
1125
|
+
EDATE: (a) => { const d = fromSerial(toNum(a[0])); d.setMonth(d.getMonth() + toNum(a[1])); return Math.floor(dateSerial(d)); },
|
|
1126
|
+
EOMONTH: (a) => { const d = fromSerial(toNum(a[0])); d.setMonth(d.getMonth() + toNum(a[1]) + 1, 0); return Math.floor(dateSerial(d)); },
|
|
1127
|
+
// DATEVALUE: (a) => { const d = new Date(toStr(a[0])); return isNaN(d.getTime()) ? "#VALUE!" : Math.floor(dateSerial(d)) },
|
|
1128
|
+
// DAYS360: (a) => days360(fromSerial(toNum(a[0])), fromSerial(toNum(a[1])), toBool(a[2])),
|
|
1129
|
+
YEARFRAC: (a) => {
|
|
1130
|
+
let s = toNum(a[0]), e = toNum(a[1]);
|
|
1131
|
+
const basis = toNum(a[2] ?? 0);
|
|
1132
|
+
if (s > e)
|
|
1133
|
+
[s, e] = [e, s];
|
|
1134
|
+
const sd = fromSerial(s), ed = fromSerial(e);
|
|
1135
|
+
switch (basis) {
|
|
1136
|
+
case 0: return days360(sd, ed, false) / 360;
|
|
1137
|
+
case 4: return days360(sd, ed, true) / 360;
|
|
1138
|
+
case 2: return (e - s) / 360;
|
|
1139
|
+
case 3: return (e - s) / 365;
|
|
1140
|
+
case 1: {
|
|
1141
|
+
const y1 = sd.getFullYear(), y2 = ed.getFullYear();
|
|
1142
|
+
let total = 0;
|
|
1143
|
+
for (let y = y1; y <= y2; y++)
|
|
1144
|
+
total += isLeap(y) ? 366 : 365;
|
|
1145
|
+
return (e - s) / (total / (y2 - y1 + 1));
|
|
1146
|
+
}
|
|
1147
|
+
default: return "#NUM!";
|
|
1148
|
+
}
|
|
1149
|
+
},
|
|
1150
|
+
TIME: (a) => (toNum(a[0]) * 3600 + toNum(a[1]) * 60 + toNum(a[2])) / 86400,
|
|
1151
|
+
YEAR: (a) => fromSerial(toNum(a[0])).getFullYear(),
|
|
1152
|
+
MONTH: (a) => fromSerial(toNum(a[0])).getMonth() + 1,
|
|
1153
|
+
DAY: (a) => fromSerial(toNum(a[0])).getDate(),
|
|
1154
|
+
HOUR: (a) => fromSerial(toNum(a[0])).getHours(),
|
|
1155
|
+
MINUTE: (a) => fromSerial(toNum(a[0])).getMinutes(),
|
|
1156
|
+
SECOND: (a) => fromSerial(toNum(a[0])).getSeconds(),
|
|
1157
|
+
WEEKDAY: (a) => { const d = fromSerial(toNum(a[0])).getDay(); const mode = toNum(a[1] ?? 1); return mode === 2 ? (d === 0 ? 7 : d) : mode === 3 ? (d === 0 ? 6 : d - 1) : d + 1; },
|
|
1158
|
+
WEEKNUM: (a) => { const d = fromSerial(toNum(a[0])); const jan1 = new Date(d.getFullYear(), 0, 1); return Math.ceil(((d.getTime() - jan1.getTime()) / 86400000 + jan1.getDay() + 1) / 7); },
|
|
1159
|
+
ISOWEEKNUM: (a) => { const d = fromSerial(toNum(a[0])); d.setHours(0, 0, 0, 0); d.setDate(d.getDate() + 4 - (d.getDay() || 7)); const y = new Date(d.getFullYear(), 0, 1); return Math.ceil(((d.getTime() - y.getTime()) / 86400000 + 1) / 7); },
|
|
1160
|
+
DAYS: (a) => toNum(a[0]) - toNum(a[1]),
|
|
1161
|
+
DAYS360: (a) => Math.round((toNum(a[0]) - toNum(a[1])) * 360 / 365),
|
|
1162
|
+
NETWORKDAYS: (a) => networkDays(toNum(a[0]), toNum(a[1]), a[2] ? flattenRange(a[2]).map(toNum) : []),
|
|
1163
|
+
WORKDAY: (a) => workday(toNum(a[0]), toNum(a[1]), a[2] ? flattenRange(a[2]).map(toNum) : []),
|
|
1164
|
+
DATEVALUE: (a) => { const d = new Date(toStr(a[0])); return isNaN(d.getTime()) ? { error: '#VALUE!' } : dateSerial(d); },
|
|
1165
|
+
TIMEVALUE: (a) => { const p = toStr(a[0]).split(':').map(Number); return (p[0] * 3600 + (p[1] ?? 0) * 60 + (p[2] ?? 0)) / 86400; },
|
|
1166
|
+
DATEDIF: (a) => { const s = fromSerial(toNum(a[0])), e = fromSerial(toNum(a[1])), u = toStr(a[2]).toUpperCase(); return dateDif(s, e, u); },
|
|
1167
|
+
};
|
|
1168
|
+
export const statistical = {
|
|
1169
|
+
PERCENTILE: (a) => pctInc(sortedNums(a[0]), toNum(a[1])),
|
|
1170
|
+
QUARTILE: (a) => { const q = Math.trunc(toNum(a[1])); return q < 0 || q > 4 ? "#NUM!" : pctInc(sortedNums(a[0]), q / 4); },
|
|
1171
|
+
PERCENTRANK: (a) => {
|
|
1172
|
+
const arr = sortedNums(a[0]), x = toNum(a[1]), sig = toNum(a[2] ?? 3), n = arr.length;
|
|
1173
|
+
if (!n || x < arr[0] || x > arr[n - 1])
|
|
1174
|
+
return "#N/A";
|
|
1175
|
+
if (n === 1)
|
|
1176
|
+
return 1;
|
|
1177
|
+
const i = arr.findIndex(v => v >= x);
|
|
1178
|
+
const r = arr[i] === x ? i / (n - 1) : (i - 1 + (x - arr[i - 1]) / (arr[i] - arr[i - 1])) / (n - 1);
|
|
1179
|
+
const f = 10 ** sig;
|
|
1180
|
+
return Math.floor(r * f) / f;
|
|
1181
|
+
},
|
|
1182
|
+
MODE: (a) => {
|
|
1183
|
+
const freq = new Map();
|
|
1184
|
+
for (const v of flattenRange(a))
|
|
1185
|
+
if (typeof v === "number")
|
|
1186
|
+
freq.set(v, (freq.get(v) ?? 0) + 1);
|
|
1187
|
+
let max = 0, mode = 0;
|
|
1188
|
+
for (const [v, f] of freq)
|
|
1189
|
+
if (f > max) {
|
|
1190
|
+
max = f;
|
|
1191
|
+
mode = v;
|
|
1192
|
+
}
|
|
1193
|
+
return max < 2 ? "#N/A" : mode;
|
|
1194
|
+
},
|
|
1195
|
+
STDEV: (a) => stddev(flattenRange(a).map(toNum), false),
|
|
1196
|
+
STDEVP: (a) => stddev(flattenRange(a).map(toNum), true),
|
|
1197
|
+
STDEVA: (a) => stddev(flattenRange(a).map(toNum), false),
|
|
1198
|
+
STDEVPA: (a) => stddev(flattenRange(a).map(toNum), true),
|
|
1199
|
+
VAR: (a) => variance(flattenRange(a).map(toNum), false),
|
|
1200
|
+
VARP: (a) => variance(flattenRange(a).map(toNum), true),
|
|
1201
|
+
VARA: (a) => variance(flattenRange(a).map(toNum), false),
|
|
1202
|
+
VARPA: (a) => variance(flattenRange(a).map(toNum), true),
|
|
1203
|
+
MEDIAN: (a) => { const n = flattenRange(a).map(toNum).sort((x, y) => x - y); const m = Math.floor(n.length / 2); return n.length % 2 ? n[m] : (n[m - 1] + n[m]) / 2; },
|
|
1204
|
+
RANK: (a) => { const v = toNum(a[0]); const arr = flattenRange(a[1]).map(toNum); const desc = a[2] !== 1; return desc ? arr.filter(x => x > v).length + 1 : arr.filter(x => x < v).length + 1; },
|
|
1205
|
+
NORMDIST: (a) => { const x = toNum(a[0]), m = toNum(a[1]), s = toNum(a[2]); return toBool(a[3]) ? normalCDF((x - m) / s) : normalPDF((x - m) / s) / s; },
|
|
1206
|
+
NORMSDIST: (a) => normalCDF(toNum(a[0])),
|
|
1207
|
+
NORMINV: (a) => normalInv(toNum(a[0]), toNum(a[1] ?? 0), toNum(a[2] ?? 1)),
|
|
1208
|
+
NORMSINV: (a) => normalInv(toNum(a[0]), 0, 1),
|
|
1209
|
+
CORREL: (a) => { const x = flattenRange(a[0]).map(toNum), y = flattenRange(a[1]).map(toNum); return correl(x, y); },
|
|
1210
|
+
COVAR: (a) => { const x = flattenRange(a[0]).map(toNum), y = flattenRange(a[1]).map(toNum); return covariance(x, y, true); },
|
|
1211
|
+
FORECAST: (a) => { const x = toNum(a[0]), y = flattenRange(a[1]).map(toNum), xs = flattenRange(a[2]).map(toNum); const [b, m] = linreg(xs, y); return m * x + b; },
|
|
1212
|
+
INTERCEPT: (a) => linreg(flattenRange(a[1]).map(toNum), flattenRange(a[0]).map(toNum))[0],
|
|
1213
|
+
SLOPE: (a) => linreg(flattenRange(a[1]).map(toNum), flattenRange(a[0]).map(toNum))[1],
|
|
1214
|
+
RSQ: (a) => Math.pow(correl(flattenRange(a[0]).map(toNum), flattenRange(a[1]).map(toNum)), 2),
|
|
1215
|
+
SKEW: (a) => { const n = flattenRange(a).map(toNum); const m = n.reduce((s, v) => s + v, 0) / n.length; const s = stddev(n, false); return n.length / (n.length - 1) / (n.length - 2) * n.reduce((acc, v) => acc + Math.pow((v - m) / s, 3), 0); },
|
|
1216
|
+
KURT: (a) => { const n = flattenRange(a).map(toNum), len = n.length; const m = n.reduce((s, v) => s + v, 0) / len; const s = stddev(n, false); return len * (len + 1) / (len - 1) / (len - 2) / (len - 3) * n.reduce((acc, v) => acc + Math.pow((v - m) / s, 4), 0) - 3 * (len - 1) * (len - 1) / (len - 2) / (len - 3); },
|
|
1217
|
+
GEOMEAN: (a) => { const n = flattenRange(a).map(toNum); return Math.pow(n.reduce((p, v) => p * v, 1), 1 / n.length); },
|
|
1218
|
+
HARMEAN: (a) => { const n = flattenRange(a).map(toNum); return n.length / n.reduce((s, v) => s + 1 / v, 0); },
|
|
1219
|
+
TRIMMEAN: (a) => { const n = flattenRange(a[0]).map(toNum).sort((x, y) => x - y); const cut = Math.floor(n.length * toNum(a[1]) / 2); const trimmed = n.slice(cut, n.length - cut); return trimmed.reduce((s, v) => s + v, 0) / trimmed.length; },
|
|
1220
|
+
FREQUENCY: (a) => {
|
|
1221
|
+
const data = flattenRange(a[0]).map(toNum), bins = flattenRange(a[1]).map(toNum).sort((x, y) => x - y);
|
|
1222
|
+
const result = Array(bins.length + 1).fill(0);
|
|
1223
|
+
for (const v of data) {
|
|
1224
|
+
let placed = false;
|
|
1225
|
+
for (let i = 0; i < bins.length; i++)
|
|
1226
|
+
if (v <= bins[i]) {
|
|
1227
|
+
result[i]++;
|
|
1228
|
+
placed = true;
|
|
1229
|
+
break;
|
|
1230
|
+
}
|
|
1231
|
+
;
|
|
1232
|
+
if (!placed)
|
|
1233
|
+
result[bins.length]++;
|
|
1234
|
+
}
|
|
1235
|
+
return result.map(v => [v]);
|
|
1236
|
+
},
|
|
1237
|
+
};
|
|
1238
|
+
export const financial = {
|
|
1239
|
+
RATE: (a) => {
|
|
1240
|
+
const n = toNum(a[0]), pmt = toNum(a[1]), pv = toNum(a[2]), fv = toNum(a[3] ?? 0), type = toNum(a[4] ?? 0);
|
|
1241
|
+
const f = (r) => r === 0 ? pv + pmt * n + fv : pv * (1 + r) ** n + pmt * (1 + r * type) * ((1 + r) ** n - 1) / r + fv;
|
|
1242
|
+
return newton(f, toNum(a[5] ?? 0.1)) ?? "#NUM!";
|
|
1243
|
+
},
|
|
1244
|
+
IRR: (a) => {
|
|
1245
|
+
const vals = flattenRange(a[0]).filter(v => typeof v === "number");
|
|
1246
|
+
if (!vals.some(v => v > 0) || !vals.some(v => v < 0))
|
|
1247
|
+
return "#NUM!";
|
|
1248
|
+
return newton(r => vals.reduce((s, v, i) => s + v / (1 + r) ** i, 0), toNum(a[1] ?? 0.1)) ?? "#NUM!";
|
|
1249
|
+
},
|
|
1250
|
+
DDB: (a) => {
|
|
1251
|
+
const cost = toNum(a[0]), salv = toNum(a[1]), life = toNum(a[2]), per = toNum(a[3]), factor = toNum(a[4] ?? 2);
|
|
1252
|
+
if (cost < 0 || salv < 0 || life <= 0 || per < 1 || per > life)
|
|
1253
|
+
return "#NUM!";
|
|
1254
|
+
let book = cost, dep = 0;
|
|
1255
|
+
for (let p = 1; p <= per; p++) {
|
|
1256
|
+
dep = Math.max(0, Math.min(book * factor / life, book - salv));
|
|
1257
|
+
book -= dep;
|
|
1258
|
+
}
|
|
1259
|
+
return dep;
|
|
1260
|
+
},
|
|
1261
|
+
DB: (a) => {
|
|
1262
|
+
const cost = toNum(a[0]), salv = toNum(a[1]), life = toNum(a[2]), per = toNum(a[3]), month = toNum(a[4] ?? 12);
|
|
1263
|
+
if (cost <= 0 || salv < 0 || life <= 0 || per < 1 || per > life + 1 || month < 1 || month > 12)
|
|
1264
|
+
return "#NUM!";
|
|
1265
|
+
const rate = Math.round((1 - (salv / cost) ** (1 / life)) * 1000) / 1000; // Excel rounds to 3 places
|
|
1266
|
+
let total = 0, dep = 0;
|
|
1267
|
+
for (let p = 1; p <= per; p++) {
|
|
1268
|
+
dep = p === 1 ? cost * rate * month / 12 : p === life + 1 ? (cost - total) * rate * (12 - month) / 12 : (cost - total) * rate;
|
|
1269
|
+
total += dep;
|
|
1270
|
+
}
|
|
1271
|
+
return dep;
|
|
1272
|
+
},
|
|
1273
|
+
PV: (a) => { const r = toNum(a[0]), n = toNum(a[1]), pmt = toNum(a[2]), fv = toNum(a[3] ?? 0), type = toNum(a[4] ?? 0); return r === 0 ? -pmt * n - fv : -(pmt * (1 + r * type) * (1 - Math.pow(1 + r, -n)) / r + fv * Math.pow(1 + r, -n)); },
|
|
1274
|
+
FV: (a) => { const r = toNum(a[0]), n = toNum(a[1]), pmt = toNum(a[2]), pv = toNum(a[3] ?? 0), type = toNum(a[4] ?? 0); return r === 0 ? -pmt * n - pv : -(pmt * (1 + r * type) * (Math.pow(1 + r, n) - 1) / r + pv * Math.pow(1 + r, n)); },
|
|
1275
|
+
PMT: (a) => { const r = toNum(a[0]), n = toNum(a[1]), pv = toNum(a[2]), fv = toNum(a[3] ?? 0), type = toNum(a[4] ?? 0); return r === 0 ? -(pv + fv) / n : r * (fv + pv * Math.pow(1 + r, n)) / ((1 + r * type) * (1 - Math.pow(1 + r, n))); },
|
|
1276
|
+
NPER: (a) => { const r = toNum(a[0]), pmt = toNum(a[1]), pv = toNum(a[2]), fv = toNum(a[3] ?? 0), type = toNum(a[4] ?? 0); return r === 0 ? -(pv + fv) / pmt : Math.log((pmt * (1 + r * type) - fv * r) / (pmt * (1 + r * type) + pv * r)) / Math.log(1 + r); },
|
|
1277
|
+
NPV: (a) => { const r = toNum(a[0]); return flattenRange(a.slice(1)).map(toNum).reduce((s, v, i) => s + v / Math.pow(1 + r, i + 1), 0); },
|
|
1278
|
+
SLN: (a) => (toNum(a[0]) - toNum(a[1])) / toNum(a[2]),
|
|
1279
|
+
SYD: (a) => { const cost = toNum(a[0]), salv = toNum(a[1]), life = toNum(a[2]), per = toNum(a[3]); return (cost - salv) * (life - per + 1) * 2 / (life * (life + 1)); },
|
|
1280
|
+
EFFECT: (a) => Math.pow(1 + toNum(a[0]) / toNum(a[1]), toNum(a[1])) - 1,
|
|
1281
|
+
NOMINAL: (a) => (Math.pow(1 + toNum(a[0]), 1 / toNum(a[1])) - 1) * toNum(a[1]),
|
|
1282
|
+
};
|
|
1283
|
+
export const info = {
|
|
1284
|
+
ERROR: { TYPE: (a) => isErr(a[0]) ? 1 : { error: '#N/A' } },
|
|
1285
|
+
INFO: (a) => ({ recalc: "Automatic", release: "1", system: "sheet" }[toStr(a[0]).toLowerCase()] ?? "#VALUE!"),
|
|
1286
|
+
ADDRESS: (a) => {
|
|
1287
|
+
const r = toNum(a[0]), c = toNum(a[1]), abs = toNum(a[2] ?? 1);
|
|
1288
|
+
if (r < 1 || c < 1 || abs < 1 || abs > 4)
|
|
1289
|
+
return "#VALUE!";
|
|
1290
|
+
let s;
|
|
1291
|
+
if (a[3] === false || a[3] === 0) {
|
|
1292
|
+
s = `R${abs === 1 || abs === 3 ? r : `[${r}]`}C${abs === 1 || abs === 2 ? c : `[${c}]`}`;
|
|
1293
|
+
}
|
|
1294
|
+
else {
|
|
1295
|
+
const col = indexToCol(c - 1);
|
|
1296
|
+
s = abs === 1 ? `$${col}$${r}` : abs === 2 ? `${col}$${r}` : abs === 3 ? `$${col}${r}` : `${col}${r}`;
|
|
1297
|
+
}
|
|
1298
|
+
return a[4] ? `${toStr(a[4])}!${s}` : s;
|
|
1299
|
+
},
|
|
1300
|
+
};
|
|
1301
|
+
export const testFn = {
|
|
1302
|
+
TEST: (a) => {
|
|
1303
|
+
const label = toStr(a[0]);
|
|
1304
|
+
const result = toBool(a[1]);
|
|
1305
|
+
return { test: true, label, pass: result };
|
|
1306
|
+
},
|
|
1307
|
+
};
|
|
1308
|
+
export const SPREADSHEET_FUNCTIONS = {
|
|
1309
|
+
...math, ...text, ...logical, ...lookup, ...dateTime, ...statistical, ...financial, ...info, ...testFn, ...lambdaFns, ...SPECIAL_FORMS,
|
|
1310
|
+
LAMBDA: (a) => a[a.length - 1],
|
|
1311
|
+
BYROW: (a) => {
|
|
1312
|
+
const data = a[0];
|
|
1313
|
+
if (!Array.isArray(data))
|
|
1314
|
+
return [[a[0]]];
|
|
1315
|
+
return data.map(row => [a[1] instanceof Function ? a[1](row) : a[1]]);
|
|
1316
|
+
},
|
|
1317
|
+
BYCOL: (a) => {
|
|
1318
|
+
const data = a[0];
|
|
1319
|
+
if (!Array.isArray(data))
|
|
1320
|
+
return [[a[0]]];
|
|
1321
|
+
const cols = (data[0]?.length ?? 1);
|
|
1322
|
+
return [Array.from({ length: cols }, (_, i) => data.map(r => r[i]))];
|
|
1323
|
+
},
|
|
1324
|
+
MAP: (a) => {
|
|
1325
|
+
const data = flattenRange(a[0]);
|
|
1326
|
+
const fn = a[1];
|
|
1327
|
+
return data.map(v => fn instanceof Function ? fn(v) : v);
|
|
1328
|
+
},
|
|
1329
|
+
REDUCE: (a) => {
|
|
1330
|
+
const init = a[0], data = flattenRange(a[1]);
|
|
1331
|
+
return data.reduce((acc, v) => v, init);
|
|
1332
|
+
},
|
|
1333
|
+
MAKEARRAY: (a) => Array.from({ length: toNum(a[0]) }, (_, r) => Array.from({ length: toNum(a[1]) }, (_, c) => [r, c])),
|
|
1334
|
+
SEQUENCE: (a) => {
|
|
1335
|
+
const rows = toNum(a[0]), cols = toNum(a[1] ?? 1), start = toNum(a[2] ?? 1), step = toNum(a[3] ?? 1);
|
|
1336
|
+
return Array.from({ length: rows }, (_, r) => Array.from({ length: cols }, (_, c) => start + step * (r * cols + c)));
|
|
1337
|
+
},
|
|
1338
|
+
RANDARRAY: (a) => Array.from({ length: toNum(a[0] ?? 1) }, () => Array.from({ length: toNum(a[1] ?? 1) }, () => Math.random())),
|
|
1339
|
+
WRAP: (a) => a[0],
|
|
1340
|
+
ANCHORARRAY: (a) => a[0],
|
|
1341
|
+
SINGLE: (a) => Array.isArray(a[0]) ? (Array.isArray(a[0][0]) ? a[0][0][0] : a[0][0]) : a[0],
|
|
1342
|
+
};
|
|
1343
|
+
export function round(v, dp) {
|
|
1344
|
+
const f = Math.pow(10, dp);
|
|
1345
|
+
return Math.round(v * f) / f;
|
|
1346
|
+
}
|
|
1347
|
+
export function gcd(a, b) { return b === 0 ? a : gcd(b, a % b); }
|
|
1348
|
+
export function combin(n, k) {
|
|
1349
|
+
if (k > n)
|
|
1350
|
+
return 0;
|
|
1351
|
+
let r = 1;
|
|
1352
|
+
for (let i = 0; i < k; i++)
|
|
1353
|
+
r = r * (n - i) / (i + 1);
|
|
1354
|
+
return Math.round(r);
|
|
1355
|
+
}
|
|
1356
|
+
export function looseEqual(a, b) {
|
|
1357
|
+
if (typeof a === 'string' && typeof b === 'string')
|
|
1358
|
+
return a.toUpperCase() === b.toUpperCase();
|
|
1359
|
+
return a === b;
|
|
1360
|
+
}
|
|
1361
|
+
export function compare(a, b) {
|
|
1362
|
+
if (typeof a === 'string' && typeof b === 'string')
|
|
1363
|
+
return a.localeCompare(b);
|
|
1364
|
+
return toNum(a) - toNum(b);
|
|
1365
|
+
}
|
|
1366
|
+
export function approxMatch(val, arr) {
|
|
1367
|
+
let result = -1;
|
|
1368
|
+
for (let i = 0; i < arr.length; i++) {
|
|
1369
|
+
if (compare(arr[i], val) <= 0)
|
|
1370
|
+
result = i;
|
|
1371
|
+
else
|
|
1372
|
+
break;
|
|
1373
|
+
}
|
|
1374
|
+
return result;
|
|
1375
|
+
}
|
|
1376
|
+
// mode 0 exact, 2 wildcard, -1 exact-or-next-smaller, 1 exact-or-next-larger. `order` is the scan order.
|
|
1377
|
+
export function findMatch(val, arr, order, mode) {
|
|
1378
|
+
if (mode === 0) {
|
|
1379
|
+
for (const i of order)
|
|
1380
|
+
if (looseEqual(arr[i], val))
|
|
1381
|
+
return i;
|
|
1382
|
+
return -1;
|
|
1383
|
+
}
|
|
1384
|
+
if (mode === 2) {
|
|
1385
|
+
for (const i of order)
|
|
1386
|
+
if (wildcardMatch(toStr(val), toStr(arr[i])))
|
|
1387
|
+
return i;
|
|
1388
|
+
return -1;
|
|
1389
|
+
}
|
|
1390
|
+
let best = -1;
|
|
1391
|
+
for (const i of order) {
|
|
1392
|
+
if (looseEqual(arr[i], val))
|
|
1393
|
+
return i;
|
|
1394
|
+
const c = compare(arr[i], val);
|
|
1395
|
+
if (mode === -1 && c < 0 && (best === -1 || compare(arr[i], arr[best]) > 0))
|
|
1396
|
+
best = i;
|
|
1397
|
+
if (mode === 1 && c > 0 && (best === -1 || compare(arr[i], arr[best]) < 0))
|
|
1398
|
+
best = i;
|
|
1399
|
+
}
|
|
1400
|
+
return best;
|
|
1401
|
+
}
|
|
1402
|
+
export function wildcardMatch(pattern, value) {
|
|
1403
|
+
const re = new RegExp('^' + pattern.replace(/\*/g, '.*').replace(/\?/g, '.') + '$', 'i');
|
|
1404
|
+
return re.test(value);
|
|
1405
|
+
}
|
|
1406
|
+
export function matchCriteria(v, crit) {
|
|
1407
|
+
if (typeof crit === 'string') {
|
|
1408
|
+
const m = crit.match(/^([<>]=?|<>)(.*)$/);
|
|
1409
|
+
if (m) {
|
|
1410
|
+
const op = m[1], rhs = m[2];
|
|
1411
|
+
const n = parseFloat(rhs);
|
|
1412
|
+
if (!isNaN(n)) {
|
|
1413
|
+
switch (op) {
|
|
1414
|
+
case '>': return toNum(v) > n;
|
|
1415
|
+
case '>=': return toNum(v) >= n;
|
|
1416
|
+
case '<': return toNum(v) < n;
|
|
1417
|
+
case '<=': return toNum(v) <= n;
|
|
1418
|
+
case '<>': return !looseEqual(v, n);
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
switch (op) {
|
|
1422
|
+
case '<>': return !looseEqual(v, rhs);
|
|
1423
|
+
default: return looseEqual(v, rhs);
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
return wildcardMatch(crit, toStr(v));
|
|
1427
|
+
}
|
|
1428
|
+
return looseEqual(v, crit);
|
|
1429
|
+
}
|
|
1430
|
+
export function stddev(vals, population) {
|
|
1431
|
+
const v = variance(vals, population);
|
|
1432
|
+
return Math.sqrt(v);
|
|
1433
|
+
}
|
|
1434
|
+
export function variance(vals, population) {
|
|
1435
|
+
const n = vals.length;
|
|
1436
|
+
if (n < 2)
|
|
1437
|
+
return 0;
|
|
1438
|
+
const m = vals.reduce((s, v) => s + v, 0) / n;
|
|
1439
|
+
const ss = vals.reduce((s, v) => s + Math.pow(v - m, 2), 0);
|
|
1440
|
+
return ss / (population ? n : n - 1);
|
|
1441
|
+
}
|
|
1442
|
+
export function correl(x, y) {
|
|
1443
|
+
const n = x.length;
|
|
1444
|
+
const mx = x.reduce((s, v) => s + v, 0) / n;
|
|
1445
|
+
const my = y.reduce((s, v) => s + v, 0) / n;
|
|
1446
|
+
const num = x.reduce((s, v, i) => s + (v - mx) * (y[i] - my), 0);
|
|
1447
|
+
const den = Math.sqrt(x.reduce((s, v) => s + Math.pow(v - mx, 2), 0) * y.reduce((s, v) => s + Math.pow(v - my, 2), 0));
|
|
1448
|
+
return den === 0 ? 0 : num / den;
|
|
1449
|
+
}
|
|
1450
|
+
export function covariance(x, y, population) {
|
|
1451
|
+
const n = x.length;
|
|
1452
|
+
const mx = x.reduce((s, v) => s + v, 0) / n;
|
|
1453
|
+
const my = y.reduce((s, v) => s + v, 0) / n;
|
|
1454
|
+
return x.reduce((s, v, i) => s + (v - mx) * (y[i] - my), 0) / (population ? n : n - 1);
|
|
1455
|
+
}
|
|
1456
|
+
export function linreg(x, y) {
|
|
1457
|
+
const n = x.length;
|
|
1458
|
+
const sx = x.reduce((s, v) => s + v, 0);
|
|
1459
|
+
const sy = y.reduce((s, v) => s + v, 0);
|
|
1460
|
+
const sxx = x.reduce((s, v) => s + v * v, 0);
|
|
1461
|
+
const sxy = x.reduce((s, v, i) => s + v * y[i], 0);
|
|
1462
|
+
const m = (n * sxy - sx * sy) / (n * sxx - sx * sx);
|
|
1463
|
+
const b = (sy - m * sx) / n;
|
|
1464
|
+
return [b, m];
|
|
1465
|
+
}
|
|
1466
|
+
export function normalPDF(z) { return Math.exp(-0.5 * z * z) / Math.sqrt(2 * Math.PI); }
|
|
1467
|
+
export function normalCDF(z) {
|
|
1468
|
+
const t = 1 / (1 + 0.2316419 * Math.abs(z));
|
|
1469
|
+
const poly = t * (0.319381530 + t * (-0.356563782 + t * (1.781477937 + t * (-1.821255978 + t * 1.330274429))));
|
|
1470
|
+
const p = 1 - normalPDF(z) * poly;
|
|
1471
|
+
return z >= 0 ? p : 1 - p;
|
|
1472
|
+
}
|
|
1473
|
+
export function normalInv(p, mu, sigma) {
|
|
1474
|
+
// Beasley-Springer-Moro approximation
|
|
1475
|
+
if (p <= 0)
|
|
1476
|
+
return -Infinity;
|
|
1477
|
+
if (p >= 1)
|
|
1478
|
+
return Infinity;
|
|
1479
|
+
const a = [2.50662823884, -18.61500062529, 41.39119773534, -25.44106049637];
|
|
1480
|
+
const b = [-8.47351093090, 23.08336743743, -21.06224101826, 3.13082909833];
|
|
1481
|
+
const c = [0.3374754822726147, 0.9761690190917186, 0.1607979714918209, 0.0276438810333863, 0.0038405729373609, 0.0003951896511349, 0.0000321767881768, 0.0000002888167364, 0.0000003960315187];
|
|
1482
|
+
const r = p < 0.5 ? p : 1 - p;
|
|
1483
|
+
let x;
|
|
1484
|
+
if (r > 0.02425) {
|
|
1485
|
+
const u = r - 0.5;
|
|
1486
|
+
const v = u * u;
|
|
1487
|
+
x = u * (((a[3] * v + a[2]) * v + a[1]) * v + a[0]) / ((((b[3] * v + b[2]) * v + b[1]) * v + b[0]) * v + 1);
|
|
1488
|
+
}
|
|
1489
|
+
else {
|
|
1490
|
+
const u = Math.sqrt(-2 * Math.log(r));
|
|
1491
|
+
x = ((((((((c[8] * u + c[7]) * u + c[6]) * u + c[5]) * u + c[4]) * u + c[3]) * u + c[2]) * u + c[1]) * u + c[0]);
|
|
1492
|
+
}
|
|
1493
|
+
return mu + sigma * (p < 0.5 ? -x : x);
|
|
1494
|
+
}
|
|
1495
|
+
export function networkDays(start, end, holidays) {
|
|
1496
|
+
let count = 0;
|
|
1497
|
+
const holidaySet = new Set(holidays);
|
|
1498
|
+
for (let d = Math.min(start, end); d <= Math.max(start, end); d++) {
|
|
1499
|
+
const day = fromSerial(d).getDay();
|
|
1500
|
+
if (day !== 0 && day !== 6 && !holidaySet.has(d))
|
|
1501
|
+
count++;
|
|
1502
|
+
}
|
|
1503
|
+
return count * (start <= end ? 1 : -1);
|
|
1504
|
+
}
|
|
1505
|
+
export function workday(start, days, holidays) {
|
|
1506
|
+
const holidaySet = new Set(holidays);
|
|
1507
|
+
let d = start, rem = Math.abs(days), dir = days >= 0 ? 1 : -1;
|
|
1508
|
+
while (rem > 0) {
|
|
1509
|
+
d += dir;
|
|
1510
|
+
const day = fromSerial(d).getDay();
|
|
1511
|
+
if (day !== 0 && day !== 6 && !holidaySet.has(d))
|
|
1512
|
+
rem--;
|
|
1513
|
+
}
|
|
1514
|
+
return d;
|
|
1515
|
+
}
|
|
1516
|
+
export function dateDif(s, e, unit) {
|
|
1517
|
+
if (s > e)
|
|
1518
|
+
return "#NUM!";
|
|
1519
|
+
const utc = (d) => Date.UTC(d.getFullYear(), d.getMonth(), d.getDate());
|
|
1520
|
+
const months = (e.getFullYear() - s.getFullYear()) * 12 + e.getMonth() - s.getMonth() - (e.getDate() < s.getDate() ? 1 : 0);
|
|
1521
|
+
switch (unit) {
|
|
1522
|
+
case "Y": return Math.floor(months / 12);
|
|
1523
|
+
case "M": return months;
|
|
1524
|
+
case "D": return Math.round((utc(e) - utc(s)) / 86400000);
|
|
1525
|
+
case "YM": return months % 12;
|
|
1526
|
+
case "MD": {
|
|
1527
|
+
let d = e.getDate() - s.getDate();
|
|
1528
|
+
if (d < 0)
|
|
1529
|
+
d += new Date(e.getFullYear(), e.getMonth(), 0).getDate();
|
|
1530
|
+
return d;
|
|
1531
|
+
}
|
|
1532
|
+
case "YD": {
|
|
1533
|
+
let adj = new Date(e.getFullYear(), s.getMonth(), s.getDate());
|
|
1534
|
+
if (adj > e)
|
|
1535
|
+
adj = new Date(e.getFullYear() - 1, s.getMonth(), s.getDate());
|
|
1536
|
+
return Math.round((utc(e) - utc(adj)) / 86400000);
|
|
1537
|
+
}
|
|
1538
|
+
default: return "#NUM!";
|
|
1539
|
+
}
|
|
1540
|
+
}
|
|
1541
|
+
export function toRoman(n) {
|
|
1542
|
+
const vals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
|
|
1543
|
+
const syms = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];
|
|
1544
|
+
let result = '';
|
|
1545
|
+
for (let i = 0; i < vals.length; i++)
|
|
1546
|
+
while (n >= vals[i]) {
|
|
1547
|
+
result += syms[i];
|
|
1548
|
+
n -= vals[i];
|
|
1549
|
+
}
|
|
1550
|
+
return result;
|
|
1551
|
+
}
|
|
1552
|
+
export function evaluate(node, ctx) {
|
|
1553
|
+
switch (node.type) {
|
|
1554
|
+
case 'Number': return node.value;
|
|
1555
|
+
case 'String': return node.value;
|
|
1556
|
+
case 'Boolean': return node.value;
|
|
1557
|
+
case 'ErrorLiteral': return { error: node.value };
|
|
1558
|
+
case 'ArrayLiteral': return node.rows.map((row) => row.map((cell) => evaluate(cell, ctx)));
|
|
1559
|
+
case 'UnaryOp': {
|
|
1560
|
+
const v = evaluate(node.operand, ctx);
|
|
1561
|
+
if (node.op === '-')
|
|
1562
|
+
return -(toNum(v));
|
|
1563
|
+
if (node.op === '%')
|
|
1564
|
+
return toNum(v) / 100;
|
|
1565
|
+
return v;
|
|
1566
|
+
}
|
|
1567
|
+
case 'BinOp': {
|
|
1568
|
+
const l = evaluate(node.left, ctx);
|
|
1569
|
+
const r = evaluate(node.right, ctx);
|
|
1570
|
+
if (isErr(l))
|
|
1571
|
+
return l;
|
|
1572
|
+
if (isErr(r))
|
|
1573
|
+
return r;
|
|
1574
|
+
switch (node.op) {
|
|
1575
|
+
case '+': return toNum(l) + toNum(r);
|
|
1576
|
+
case '-': return toNum(l) - toNum(r);
|
|
1577
|
+
case '*': return toNum(l) * toNum(r);
|
|
1578
|
+
case '/': {
|
|
1579
|
+
const d = toNum(r);
|
|
1580
|
+
return d === 0 ? { error: '#DIV/0!' } : toNum(l) / d;
|
|
1581
|
+
}
|
|
1582
|
+
case '^': return Math.pow(toNum(l), toNum(r));
|
|
1583
|
+
case '&': return toStr(l) + toStr(r);
|
|
1584
|
+
case '=':
|
|
1585
|
+
case '==': return looseEq(l, r);
|
|
1586
|
+
case '<>': return !looseEq(l, r);
|
|
1587
|
+
case '<': return toNum(l) < toNum(r);
|
|
1588
|
+
case '<=': return toNum(l) <= toNum(r);
|
|
1589
|
+
case '>': return toNum(l) > toNum(r);
|
|
1590
|
+
case '>=': return toNum(l) >= toNum(r);
|
|
1591
|
+
}
|
|
1592
|
+
return { error: '#VALUE!' };
|
|
1593
|
+
}
|
|
1594
|
+
case 'CellRef': {
|
|
1595
|
+
const key = cellKey(node.col, node.row, node.sheet);
|
|
1596
|
+
return resolveCell(key, ctx);
|
|
1597
|
+
}
|
|
1598
|
+
case 'Range': {
|
|
1599
|
+
return expandRange(node, ctx);
|
|
1600
|
+
}
|
|
1601
|
+
case 'ColRange': {
|
|
1602
|
+
return { type: 'ColRange', start: node.start, end: node.end };
|
|
1603
|
+
}
|
|
1604
|
+
case 'Name': {
|
|
1605
|
+
const named = ctx.namedRanges.get(node.name);
|
|
1606
|
+
if (named) {
|
|
1607
|
+
const parsed = parseRangeStr(named);
|
|
1608
|
+
if (parsed)
|
|
1609
|
+
return expandRange(parsed, ctx);
|
|
1610
|
+
}
|
|
1611
|
+
return { error: '#NAME?' };
|
|
1612
|
+
}
|
|
1613
|
+
case 'StructuredRef': return { error: '#REF!' };
|
|
1614
|
+
case 'FunctionCall': {
|
|
1615
|
+
const fn = SPREADSHEET_FUNCTIONS[node.name];
|
|
1616
|
+
if (!fn)
|
|
1617
|
+
return { error: `#NAME? (${node.name})` };
|
|
1618
|
+
const args = node.args.map((a) => evaluate(a, ctx));
|
|
1619
|
+
try {
|
|
1620
|
+
return fn(args, ctx);
|
|
1621
|
+
}
|
|
1622
|
+
catch (e) {
|
|
1623
|
+
return { error: e instanceof Error ? e.message : '#VALUE!' };
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
default: return { error: '#VALUE!' };
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
export function toNum(v) {
|
|
1630
|
+
if (typeof v === 'number')
|
|
1631
|
+
return v;
|
|
1632
|
+
if (typeof v === 'boolean')
|
|
1633
|
+
return v ? 1 : 0;
|
|
1634
|
+
if (typeof v === 'string') {
|
|
1635
|
+
const n = parseFloat(v);
|
|
1636
|
+
if (!isNaN(n))
|
|
1637
|
+
return n;
|
|
1638
|
+
}
|
|
1639
|
+
return 0;
|
|
1640
|
+
}
|
|
1641
|
+
export function toStr(v) {
|
|
1642
|
+
if (v === null || v === undefined)
|
|
1643
|
+
return '';
|
|
1644
|
+
if (typeof v === 'boolean')
|
|
1645
|
+
return v ? 'TRUE' : 'FALSE';
|
|
1646
|
+
return String(v);
|
|
1647
|
+
}
|
|
1648
|
+
export function toBool(v) {
|
|
1649
|
+
if (typeof v === 'boolean')
|
|
1650
|
+
return v;
|
|
1651
|
+
if (typeof v === 'number')
|
|
1652
|
+
return v !== 0;
|
|
1653
|
+
if (typeof v === 'string')
|
|
1654
|
+
return v.toUpperCase() === 'TRUE';
|
|
1655
|
+
return false;
|
|
1656
|
+
}
|
|
1657
|
+
export function looseEq(a, b) {
|
|
1658
|
+
if (typeof a === 'string' && typeof b === 'string')
|
|
1659
|
+
return a.toUpperCase() === b.toUpperCase();
|
|
1660
|
+
return a === b;
|
|
1661
|
+
}
|
|
1662
|
+
export function cellKey(col, row, sheet) {
|
|
1663
|
+
return sheet ? `${sheet}!${col}${row}` : `${col}${row}`;
|
|
1664
|
+
}
|
|
1665
|
+
export function cellAt(ctx, key) {
|
|
1666
|
+
if (!ctx.store.has(key))
|
|
1667
|
+
ctx.fetch?.(key);
|
|
1668
|
+
return ctx.store.get(key);
|
|
1669
|
+
}
|
|
1670
|
+
export function resolveCell(key, ctx) {
|
|
1671
|
+
if (!ctx.store.has(key))
|
|
1672
|
+
ctx.fetch?.(key);
|
|
1673
|
+
const computed = ctx.computed.get(key);
|
|
1674
|
+
if (computed !== undefined)
|
|
1675
|
+
return computed;
|
|
1676
|
+
const cell = ctx.store.get(key);
|
|
1677
|
+
if (!cell)
|
|
1678
|
+
return 0;
|
|
1679
|
+
if (isFormula(cell.raw))
|
|
1680
|
+
return cell.computed ?? 0;
|
|
1681
|
+
return cell.raw ?? 0;
|
|
1682
|
+
}
|
|
1683
|
+
const KEY_RE = /^(?:(.+)!)?([A-Z]+)(\d+)$/;
|
|
1684
|
+
const maxRowIn = (g, sheet) => {
|
|
1685
|
+
let r = 0;
|
|
1686
|
+
for (const k of g.cells.keys()) {
|
|
1687
|
+
const m = KEY_RE.exec(k);
|
|
1688
|
+
if (m && (m[1] ?? undefined) === sheet)
|
|
1689
|
+
r = Math.max(r, +m[3]);
|
|
1690
|
+
}
|
|
1691
|
+
return r;
|
|
1692
|
+
};
|
|
1693
|
+
export function evaluateSpreadsheetAst(ast, graph, self) {
|
|
1694
|
+
return evaluateAst(ast, {
|
|
1695
|
+
store: graph.cells, computed: graph.computed, fetch: graph.fetch,
|
|
1696
|
+
self, sheet: self ? parseCellRef(self).sheet : undefined,
|
|
1697
|
+
extent: (sh) => Math.max(graph.extent?.(sh) ?? 0, maxRowIn(graph, sh)),
|
|
1698
|
+
});
|
|
1699
|
+
}
|
|
1700
|
+
export function expandRange(node, ctx) {
|
|
1701
|
+
const sc = colToIndex(node.start.col), ec = colToIndex(node.end.col);
|
|
1702
|
+
const sr = node.start.row, er = node.end.row;
|
|
1703
|
+
const rows = [];
|
|
1704
|
+
for (let r = Math.min(sr, er); r <= Math.max(sr, er); r++) {
|
|
1705
|
+
const row = [];
|
|
1706
|
+
for (let c = Math.min(sc, ec); c <= Math.max(sc, ec); c++) {
|
|
1707
|
+
row.push(resolveCell(cellKey(indexToCol(c), r, node.sheet), ctx));
|
|
1708
|
+
}
|
|
1709
|
+
rows.push(row);
|
|
1710
|
+
}
|
|
1711
|
+
return rows;
|
|
1712
|
+
}
|
|
1713
|
+
export function flattenRange(v) {
|
|
1714
|
+
if (!Array.isArray(v))
|
|
1715
|
+
return [v];
|
|
1716
|
+
return v.flatMap(flattenRange);
|
|
1717
|
+
}
|
|
1718
|
+
export function colToIndex(col) {
|
|
1719
|
+
let n = 0;
|
|
1720
|
+
for (let i = 0; i < col.length; i++)
|
|
1721
|
+
n = n * 26 + col.charCodeAt(i) - 64;
|
|
1722
|
+
return n - 1;
|
|
1723
|
+
}
|
|
1724
|
+
export function indexToCol(n) {
|
|
1725
|
+
let s = '';
|
|
1726
|
+
let m = n + 1;
|
|
1727
|
+
while (m > 0) {
|
|
1728
|
+
s = String.fromCharCode(((m - 1) % 26) + 65) + s;
|
|
1729
|
+
m = Math.floor((m - 1) / 26);
|
|
1730
|
+
}
|
|
1731
|
+
return s;
|
|
1732
|
+
}
|
|
1733
|
+
export function parseRangeStr(ref) {
|
|
1734
|
+
const m = ref.match(/^(?:(.+)!)?([A-Z]+)(\d+):([A-Z]+)(\d+)$/);
|
|
1735
|
+
if (!m)
|
|
1736
|
+
return null;
|
|
1737
|
+
return { sheet: m[1], start: { col: m[2], row: parseInt(m[3]) }, end: { col: m[4], row: parseInt(m[5]) } };
|
|
1738
|
+
}
|
|
1739
|
+
export function tokenize(src) {
|
|
1740
|
+
const toks = [];
|
|
1741
|
+
let i = 0;
|
|
1742
|
+
const len = src.length;
|
|
1743
|
+
while (i < len) {
|
|
1744
|
+
const pos = i;
|
|
1745
|
+
const ch = src[i];
|
|
1746
|
+
if (ch === ' ' || ch === '\t' || ch === '\r' || ch === '\n') {
|
|
1747
|
+
i++;
|
|
1748
|
+
continue;
|
|
1749
|
+
}
|
|
1750
|
+
if (ch === '"') {
|
|
1751
|
+
let s = '';
|
|
1752
|
+
i++;
|
|
1753
|
+
while (i < len) {
|
|
1754
|
+
if (src[i] === '"') {
|
|
1755
|
+
if (src[i + 1] === '"') {
|
|
1756
|
+
s += '"';
|
|
1757
|
+
i += 2;
|
|
1758
|
+
}
|
|
1759
|
+
else {
|
|
1760
|
+
i++;
|
|
1761
|
+
break;
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
else {
|
|
1765
|
+
s += src[i++];
|
|
1766
|
+
}
|
|
1767
|
+
}
|
|
1768
|
+
toks.push({ type: 'STR', value: s, pos });
|
|
1769
|
+
continue;
|
|
1770
|
+
}
|
|
1771
|
+
if (/\d/.test(ch) || (ch === '.' && /\d/.test(src[i + 1] ?? ''))) {
|
|
1772
|
+
let s = '';
|
|
1773
|
+
while (i < len && /[\d.eE+\-]/.test(src[i])) {
|
|
1774
|
+
if ((src[i] === '+' || src[i] === '-') && !/[eE]/.test(src[i - 1] ?? ''))
|
|
1775
|
+
break;
|
|
1776
|
+
s += src[i++];
|
|
1777
|
+
}
|
|
1778
|
+
toks.push({ type: 'NUM', value: s, pos });
|
|
1779
|
+
continue;
|
|
1780
|
+
}
|
|
1781
|
+
if (/[A-Za-z_]/.test(ch) || ch === "'") {
|
|
1782
|
+
// sheet name with spaces: 'Sheet Name'!
|
|
1783
|
+
if (ch === "'") {
|
|
1784
|
+
let s = '';
|
|
1785
|
+
i++;
|
|
1786
|
+
while (i < len && src[i] !== "'")
|
|
1787
|
+
s += src[i++];
|
|
1788
|
+
i++; // closing '
|
|
1789
|
+
if (src[i] === '!') {
|
|
1790
|
+
toks.push({ type: 'SHEET_PREFIX', value: s, pos });
|
|
1791
|
+
i++;
|
|
1792
|
+
continue;
|
|
1793
|
+
}
|
|
1794
|
+
toks.push({ type: 'IDENT', value: s, pos });
|
|
1795
|
+
continue;
|
|
1796
|
+
}
|
|
1797
|
+
let s = '';
|
|
1798
|
+
while (i < len && /[\w$]/.test(src[i]))
|
|
1799
|
+
s += src[i++];
|
|
1800
|
+
if (src[i] === '!') {
|
|
1801
|
+
toks.push({ type: 'SHEET_PREFIX', value: s, pos });
|
|
1802
|
+
i++;
|
|
1803
|
+
continue;
|
|
1804
|
+
}
|
|
1805
|
+
const up = s.toUpperCase();
|
|
1806
|
+
if (up === 'TRUE' || up === 'FALSE') {
|
|
1807
|
+
toks.push({ type: 'BOOL', value: up, pos });
|
|
1808
|
+
continue;
|
|
1809
|
+
}
|
|
1810
|
+
toks.push({ type: 'IDENT', value: s, pos });
|
|
1811
|
+
continue;
|
|
1812
|
+
}
|
|
1813
|
+
switch (ch) {
|
|
1814
|
+
case '+':
|
|
1815
|
+
toks.push({ type: 'PLUS', value: '+', pos });
|
|
1816
|
+
i++;
|
|
1817
|
+
break;
|
|
1818
|
+
case '-':
|
|
1819
|
+
toks.push({ type: 'MINUS', value: '-', pos });
|
|
1820
|
+
i++;
|
|
1821
|
+
break;
|
|
1822
|
+
case '*':
|
|
1823
|
+
toks.push({ type: 'STAR', value: '*', pos });
|
|
1824
|
+
i++;
|
|
1825
|
+
break;
|
|
1826
|
+
case '/':
|
|
1827
|
+
toks.push({ type: 'SLASH', value: '/', pos });
|
|
1828
|
+
i++;
|
|
1829
|
+
break;
|
|
1830
|
+
case '^':
|
|
1831
|
+
toks.push({ type: 'CARET', value: '^', pos });
|
|
1832
|
+
i++;
|
|
1833
|
+
break;
|
|
1834
|
+
case '%':
|
|
1835
|
+
toks.push({ type: 'PERCENT', value: '%', pos });
|
|
1836
|
+
i++;
|
|
1837
|
+
break;
|
|
1838
|
+
case '&':
|
|
1839
|
+
toks.push({ type: 'AMP', value: '&', pos });
|
|
1840
|
+
i++;
|
|
1841
|
+
break;
|
|
1842
|
+
case '(':
|
|
1843
|
+
toks.push({ type: 'LPAREN', value: '(', pos });
|
|
1844
|
+
i++;
|
|
1845
|
+
break;
|
|
1846
|
+
case ')':
|
|
1847
|
+
toks.push({ type: 'RPAREN', value: ')', pos });
|
|
1848
|
+
i++;
|
|
1849
|
+
break;
|
|
1850
|
+
case '{':
|
|
1851
|
+
toks.push({ type: 'LBRACE', value: '{', pos });
|
|
1852
|
+
i++;
|
|
1853
|
+
break;
|
|
1854
|
+
case '}':
|
|
1855
|
+
toks.push({ type: 'RBRACE', value: '}', pos });
|
|
1856
|
+
i++;
|
|
1857
|
+
break;
|
|
1858
|
+
case ':':
|
|
1859
|
+
toks.push({ type: 'COLON', value: ':', pos });
|
|
1860
|
+
i++;
|
|
1861
|
+
break;
|
|
1862
|
+
case ';':
|
|
1863
|
+
toks.push({ type: 'SEMI', value: ';', pos });
|
|
1864
|
+
i++;
|
|
1865
|
+
break;
|
|
1866
|
+
case ',':
|
|
1867
|
+
toks.push({ type: 'COMMA', value: ',', pos });
|
|
1868
|
+
i++;
|
|
1869
|
+
break;
|
|
1870
|
+
case '!':
|
|
1871
|
+
toks.push({ type: 'BANG', value: '!', pos });
|
|
1872
|
+
i++;
|
|
1873
|
+
break;
|
|
1874
|
+
case '#': {
|
|
1875
|
+
let s = '#';
|
|
1876
|
+
i++;
|
|
1877
|
+
while (i < len && /[A-Z\/!?]/.test(src[i]))
|
|
1878
|
+
s += src[i++];
|
|
1879
|
+
toks.push({ type: 'ERROR', value: s, pos });
|
|
1880
|
+
break;
|
|
1881
|
+
}
|
|
1882
|
+
case '=':
|
|
1883
|
+
if (src[i + 1] === '=') {
|
|
1884
|
+
toks.push({ type: 'EQ', value: '==', pos });
|
|
1885
|
+
i += 2;
|
|
1886
|
+
}
|
|
1887
|
+
else {
|
|
1888
|
+
toks.push({ type: 'EQ', value: '=', pos });
|
|
1889
|
+
i++;
|
|
1890
|
+
}
|
|
1891
|
+
;
|
|
1892
|
+
break;
|
|
1893
|
+
case '<':
|
|
1894
|
+
if (src[i + 1] === '=') {
|
|
1895
|
+
toks.push({ type: 'LTE', value: '<=', pos });
|
|
1896
|
+
i += 2;
|
|
1897
|
+
}
|
|
1898
|
+
else if (src[i + 1] === '>') {
|
|
1899
|
+
toks.push({ type: 'NEQ', value: '<>', pos });
|
|
1900
|
+
i += 2;
|
|
1901
|
+
}
|
|
1902
|
+
else {
|
|
1903
|
+
toks.push({ type: 'LT', value: '<', pos });
|
|
1904
|
+
i++;
|
|
1905
|
+
}
|
|
1906
|
+
;
|
|
1907
|
+
break;
|
|
1908
|
+
case '>':
|
|
1909
|
+
if (src[i + 1] === '=') {
|
|
1910
|
+
toks.push({ type: 'GTE', value: '>=', pos });
|
|
1911
|
+
i += 2;
|
|
1912
|
+
}
|
|
1913
|
+
else {
|
|
1914
|
+
toks.push({ type: 'GT', value: '>', pos });
|
|
1915
|
+
i++;
|
|
1916
|
+
}
|
|
1917
|
+
;
|
|
1918
|
+
break;
|
|
1919
|
+
default: i++;
|
|
1920
|
+
}
|
|
1921
|
+
}
|
|
1922
|
+
toks.push({ type: 'EOF', value: '', pos: i });
|
|
1923
|
+
return toks;
|
|
1924
|
+
}
|
|
1925
|
+
export function parseFormula(raw) {
|
|
1926
|
+
const src = raw[0] === '=' ? raw.slice(1) : raw;
|
|
1927
|
+
return new Parser(src).parse();
|
|
1928
|
+
}
|
|
1929
|
+
export class Parser {
|
|
1930
|
+
toks;
|
|
1931
|
+
pos = 0;
|
|
1932
|
+
constructor(src) {
|
|
1933
|
+
this.toks = tokenize(src);
|
|
1934
|
+
}
|
|
1935
|
+
peek() { return this.toks[this.pos]; }
|
|
1936
|
+
eat() { return this.toks[this.pos++]; }
|
|
1937
|
+
expect(type) {
|
|
1938
|
+
const t = this.eat();
|
|
1939
|
+
if (t.type !== type)
|
|
1940
|
+
throw new Error(`Expected ${type} at pos ${t.pos}, got ${t.type}`);
|
|
1941
|
+
return t;
|
|
1942
|
+
}
|
|
1943
|
+
match(...types) { return types.includes(this.peek().type); }
|
|
1944
|
+
parse() {
|
|
1945
|
+
const node = this.parseExpr();
|
|
1946
|
+
if (this.peek().type !== 'EOF')
|
|
1947
|
+
throw new Error(`Unexpected token at pos ${this.peek().pos}`);
|
|
1948
|
+
return node;
|
|
1949
|
+
}
|
|
1950
|
+
// Expr → Comparison
|
|
1951
|
+
parseExpr() { return this.parseComparison(); }
|
|
1952
|
+
parseComparison() {
|
|
1953
|
+
let left = this.parseConcat();
|
|
1954
|
+
while (this.match('EQ', 'NEQ', 'LT', 'LTE', 'GT', 'GTE')) {
|
|
1955
|
+
const op = this.eat().value;
|
|
1956
|
+
left = { type: 'BinOp', op, left, right: this.parseConcat() };
|
|
1957
|
+
}
|
|
1958
|
+
return left;
|
|
1959
|
+
}
|
|
1960
|
+
parseConcat() {
|
|
1961
|
+
let left = this.parseAddSub();
|
|
1962
|
+
while (this.match('AMP')) {
|
|
1963
|
+
this.eat();
|
|
1964
|
+
left = { type: 'BinOp', op: '&', left, right: this.parseAddSub() };
|
|
1965
|
+
}
|
|
1966
|
+
return left;
|
|
1967
|
+
}
|
|
1968
|
+
parseAddSub1() {
|
|
1969
|
+
let left = this.parseMulDiv();
|
|
1970
|
+
while (this.match('PLUS', 'MINUS')) {
|
|
1971
|
+
const op = this.eat().value;
|
|
1972
|
+
left = { type: 'BinOp', op, left, right: this.parseMulDiv() };
|
|
1973
|
+
}
|
|
1974
|
+
return left;
|
|
1975
|
+
}
|
|
1976
|
+
parseAddSub() {
|
|
1977
|
+
let left = this.parseMulDiv();
|
|
1978
|
+
while (this.match("PLUS", "MINUS")) {
|
|
1979
|
+
const op = this.eat().value;
|
|
1980
|
+
left = { type: "BinOp", op, left, right: this.parseMulDiv() };
|
|
1981
|
+
}
|
|
1982
|
+
return left;
|
|
1983
|
+
}
|
|
1984
|
+
parseMulDiv() {
|
|
1985
|
+
let left = this.parseExponent();
|
|
1986
|
+
while (this.match('STAR', 'SLASH')) {
|
|
1987
|
+
const op = this.eat().value;
|
|
1988
|
+
left = { type: 'BinOp', op, left, right: this.parseExponent() };
|
|
1989
|
+
}
|
|
1990
|
+
return left;
|
|
1991
|
+
}
|
|
1992
|
+
parseExponent() {
|
|
1993
|
+
let left = this.parseUnary();
|
|
1994
|
+
if (this.match('CARET')) {
|
|
1995
|
+
this.eat();
|
|
1996
|
+
return { type: 'BinOp', op: '^', left, right: this.parseExponent() };
|
|
1997
|
+
}
|
|
1998
|
+
return left;
|
|
1999
|
+
}
|
|
2000
|
+
parseUnary() {
|
|
2001
|
+
if (this.match('MINUS')) {
|
|
2002
|
+
this.eat();
|
|
2003
|
+
return { type: 'UnaryOp', op: '-', operand: this.parsePostfix() };
|
|
2004
|
+
}
|
|
2005
|
+
if (this.match('PLUS')) {
|
|
2006
|
+
this.eat();
|
|
2007
|
+
return this.parsePostfix();
|
|
2008
|
+
}
|
|
2009
|
+
return this.parsePostfix();
|
|
2010
|
+
}
|
|
2011
|
+
parsePostfix() {
|
|
2012
|
+
let node = this.parsePrimary();
|
|
2013
|
+
if (this.match('PERCENT')) {
|
|
2014
|
+
this.eat();
|
|
2015
|
+
node = { type: 'UnaryOp', op: '%', operand: node };
|
|
2016
|
+
}
|
|
2017
|
+
return node;
|
|
2018
|
+
}
|
|
2019
|
+
parsePrimary() {
|
|
2020
|
+
const t = this.peek();
|
|
2021
|
+
// Array literal {1,2;3,4}
|
|
2022
|
+
if (t.type === 'LBRACE') {
|
|
2023
|
+
this.eat();
|
|
2024
|
+
const rows = [[]];
|
|
2025
|
+
while (!this.match('RBRACE') && !this.match('EOF')) {
|
|
2026
|
+
rows[rows.length - 1].push(this.parseExpr());
|
|
2027
|
+
if (this.match('SEMI')) {
|
|
2028
|
+
this.eat();
|
|
2029
|
+
rows.push([]);
|
|
2030
|
+
}
|
|
2031
|
+
else if (this.match('COMMA'))
|
|
2032
|
+
this.eat();
|
|
2033
|
+
}
|
|
2034
|
+
this.expect('RBRACE');
|
|
2035
|
+
return { type: 'ArrayLiteral', rows };
|
|
2036
|
+
}
|
|
2037
|
+
// Parenthesised
|
|
2038
|
+
if (t.type === 'LPAREN') {
|
|
2039
|
+
this.eat();
|
|
2040
|
+
const inner = this.parseExpr();
|
|
2041
|
+
this.expect('RPAREN');
|
|
2042
|
+
return inner;
|
|
2043
|
+
}
|
|
2044
|
+
// Number
|
|
2045
|
+
if (t.type === 'NUM') {
|
|
2046
|
+
this.eat();
|
|
2047
|
+
return { type: 'Number', value: parseFloat(t.value) };
|
|
2048
|
+
}
|
|
2049
|
+
// String
|
|
2050
|
+
if (t.type === 'STR') {
|
|
2051
|
+
this.eat();
|
|
2052
|
+
return { type: 'String', value: t.value };
|
|
2053
|
+
}
|
|
2054
|
+
// Bool
|
|
2055
|
+
if (t.type === 'BOOL') {
|
|
2056
|
+
this.eat();
|
|
2057
|
+
return { type: 'Boolean', value: t.value === 'TRUE' };
|
|
2058
|
+
}
|
|
2059
|
+
// Error literal
|
|
2060
|
+
if (t.type === 'ERROR') {
|
|
2061
|
+
this.eat();
|
|
2062
|
+
return { type: 'ErrorLiteral', value: t.value };
|
|
2063
|
+
}
|
|
2064
|
+
// Sheet prefix followed by cell/range
|
|
2065
|
+
if (t.type === 'SHEET_PREFIX') {
|
|
2066
|
+
this.eat();
|
|
2067
|
+
const sheet = t.value;
|
|
2068
|
+
const ref = this.parseCellOrRange(sheet);
|
|
2069
|
+
return ref;
|
|
2070
|
+
}
|
|
2071
|
+
// IDENT — could be: function call, named range, cell ref, range
|
|
2072
|
+
if (t.type === 'IDENT') {
|
|
2073
|
+
this.eat();
|
|
2074
|
+
// Function call
|
|
2075
|
+
if (this.peek().type === 'LPAREN') {
|
|
2076
|
+
this.eat();
|
|
2077
|
+
const args = [];
|
|
2078
|
+
if (!this.match('RPAREN')) {
|
|
2079
|
+
args.push(this.parseExpr());
|
|
2080
|
+
while (this.match('COMMA', 'SEMI')) {
|
|
2081
|
+
this.eat();
|
|
2082
|
+
args.push(this.parseExpr());
|
|
2083
|
+
}
|
|
2084
|
+
}
|
|
2085
|
+
this.expect('RPAREN');
|
|
2086
|
+
return { type: 'FunctionCall', name: t.value.toUpperCase(), args };
|
|
2087
|
+
}
|
|
2088
|
+
// Cell ref or range
|
|
2089
|
+
const cellMatch = t.value.match(/^([A-Za-z]+)(\d+)$/);
|
|
2090
|
+
if (cellMatch) {
|
|
2091
|
+
const col = cellMatch[1].toUpperCase();
|
|
2092
|
+
const row = parseInt(cellMatch[2]);
|
|
2093
|
+
if (this.peek().type === 'COLON') {
|
|
2094
|
+
this.eat();
|
|
2095
|
+
const t2 = this.peek();
|
|
2096
|
+
// end of range could be IDENT
|
|
2097
|
+
if (t2.type === 'IDENT') {
|
|
2098
|
+
this.eat();
|
|
2099
|
+
const m2 = t2.value.match(/^([A-Za-z]+)(\d+)?$/);
|
|
2100
|
+
if (m2) {
|
|
2101
|
+
const col2 = m2[1].toUpperCase();
|
|
2102
|
+
const row2 = m2[2] ? parseInt(m2[2]) : row;
|
|
2103
|
+
return { type: 'Range', start: { col, row }, end: { col: col2, row: row2 } };
|
|
2104
|
+
}
|
|
2105
|
+
}
|
|
2106
|
+
return { type: 'CellRef', col, row };
|
|
2107
|
+
}
|
|
2108
|
+
return { type: 'CellRef', col, row };
|
|
2109
|
+
}
|
|
2110
|
+
// Col-only range e.g. A:A
|
|
2111
|
+
const colOnly = t.value.match(/^([A-Za-z]+)$/);
|
|
2112
|
+
if (colOnly && this.peek().type === 'COLON') {
|
|
2113
|
+
this.eat();
|
|
2114
|
+
const t2 = this.peek();
|
|
2115
|
+
if (t2.type === 'IDENT' && t2.value.match(/^[A-Za-z]+$/)) {
|
|
2116
|
+
this.eat();
|
|
2117
|
+
return { type: 'ColRange', start: t.value.toUpperCase(), end: t2.value.toUpperCase() };
|
|
2118
|
+
}
|
|
2119
|
+
}
|
|
2120
|
+
// Named range / structured ref
|
|
2121
|
+
if (t.value.includes('[')) {
|
|
2122
|
+
return { type: 'StructuredRef', raw: t.value };
|
|
2123
|
+
}
|
|
2124
|
+
return { type: 'Name', name: t.value };
|
|
2125
|
+
}
|
|
2126
|
+
throw new Error(`Unexpected token "${t.value}" (${t.type}) at pos ${t.pos}`);
|
|
2127
|
+
}
|
|
2128
|
+
parseCellOrRange(sheet) {
|
|
2129
|
+
const t = this.peek();
|
|
2130
|
+
if (t.type !== 'IDENT')
|
|
2131
|
+
throw new Error(`Expected cell ref after sheet prefix at pos ${t.pos}`);
|
|
2132
|
+
this.eat();
|
|
2133
|
+
const m = t.value.match(/^([A-Za-z]+)(\d+)$/);
|
|
2134
|
+
if (!m) {
|
|
2135
|
+
if (/^[A-Za-z]+$/.test(t.value) && this.peek().type === 'COLON') { // Sheet!A:A
|
|
2136
|
+
this.eat();
|
|
2137
|
+
const t2 = this.peek();
|
|
2138
|
+
if (t2.type === 'IDENT' && /^[A-Za-z]+$/.test(t2.value)) {
|
|
2139
|
+
this.eat();
|
|
2140
|
+
return { type: 'ColRange', sheet, start: t.value.toUpperCase(), end: t2.value.toUpperCase() };
|
|
2141
|
+
}
|
|
2142
|
+
}
|
|
2143
|
+
return { type: 'Name', name: t.value, sheet };
|
|
2144
|
+
}
|
|
2145
|
+
const col = m[1].toUpperCase();
|
|
2146
|
+
const row = parseInt(m[2]);
|
|
2147
|
+
if (this.peek().type === 'COLON') {
|
|
2148
|
+
this.eat();
|
|
2149
|
+
const t2 = this.peek();
|
|
2150
|
+
if (t2.type === 'IDENT') {
|
|
2151
|
+
this.eat();
|
|
2152
|
+
const m2 = t2.value.match(/^([A-Za-z]+)(\d+)?$/);
|
|
2153
|
+
if (m2)
|
|
2154
|
+
return { type: 'Range', sheet, start: { col, row }, end: { col: m2[1].toUpperCase(), row: m2[2] ? parseInt(m2[2]) : row } };
|
|
2155
|
+
}
|
|
2156
|
+
}
|
|
2157
|
+
return { type: 'CellRef', sheet, col, row };
|
|
2158
|
+
}
|
|
2159
|
+
}
|
|
2160
|
+
function isComplex(node) {
|
|
2161
|
+
const children = node.properties || node.elements || [];
|
|
2162
|
+
return children.some((c) => {
|
|
2163
|
+
const val = c.type === 'Property' ? c.value : c;
|
|
2164
|
+
return val?.type === 'ObjectExpression' || val?.type === 'ArrayExpression';
|
|
2165
|
+
});
|
|
2166
|
+
}
|
|
2167
|
+
export function formatBifrost(filePath) {
|
|
2168
|
+
const ast = parseAST(filePath);
|
|
2169
|
+
const generator = Registry.maelstrom.rift.use('generator', 0);
|
|
2170
|
+
walkTSNodes(ast.raw, (node) => {
|
|
2171
|
+
if (['ObjectExpression', 'ArrayExpression', 'CallExpression'].includes(node.type)) {
|
|
2172
|
+
const dryRun = generator.default(node, { compact: true, minified: true }).code;
|
|
2173
|
+
const fits = dryRun.length <= 800;
|
|
2174
|
+
const flat = !isComplex(node);
|
|
2175
|
+
if (fits && flat) {
|
|
2176
|
+
node.compact = true;
|
|
2177
|
+
node.retainLines = true;
|
|
2178
|
+
}
|
|
2179
|
+
else {
|
|
2180
|
+
node.compact = false;
|
|
2181
|
+
node.retainLines = false;
|
|
2182
|
+
}
|
|
2183
|
+
}
|
|
2184
|
+
});
|
|
2185
|
+
// 2. Hard-coded branding based on your reference
|
|
2186
|
+
return generator.default(ast.raw, {
|
|
2187
|
+
indent: "\t", // Always Tabs
|
|
2188
|
+
quotes: "double", // Always Double Quotes
|
|
2189
|
+
semi: true, // Always Semicolons
|
|
2190
|
+
compact: false, // Controlled by node-level hints above
|
|
2191
|
+
retainLines: false,
|
|
2192
|
+
bracketSpacing: true, // { label: "..." } instead of {label:"..."}
|
|
2193
|
+
jsescOption: { minimal: true }
|
|
2194
|
+
}).code;
|
|
2195
|
+
}
|
|
2196
|
+
export function parseASTFromContent(content, filePath) {
|
|
2197
|
+
const lang = detectLang(filePath);
|
|
2198
|
+
switch (lang) {
|
|
2199
|
+
case 'ts':
|
|
2200
|
+
case 'tsx':
|
|
2201
|
+
case 'js':
|
|
2202
|
+
case 'jsx': {
|
|
2203
|
+
const raw = parseTS(content, {
|
|
2204
|
+
jsx: lang === 'tsx' || lang === 'jsx',
|
|
2205
|
+
loc: true,
|
|
2206
|
+
range: true,
|
|
2207
|
+
tokens: false,
|
|
2208
|
+
comment: false,
|
|
2209
|
+
});
|
|
2210
|
+
return { lang, filePath, raw: content };
|
|
2211
|
+
}
|
|
2212
|
+
case 'css':
|
|
2213
|
+
case 'md':
|
|
2214
|
+
case 'json':
|
|
2215
|
+
case 'jsonc':
|
|
2216
|
+
// For non-JS languages, you'd need similar handling
|
|
2217
|
+
return parseAST(filePath); // Fallback to file-based parsing
|
|
2218
|
+
}
|
|
2219
|
+
}
|
|
2220
|
+
export function regenerateCode(ast) {
|
|
2221
|
+
const generator = Registry.maelstrom.rift.use('generator', 0);
|
|
2222
|
+
return generator.default(ast.raw, { retainLines: true }).code;
|
|
2223
|
+
}
|
|
2224
|
+
function detectLang(filePath) {
|
|
2225
|
+
const ext = path.extname(filePath).replace('.', '').toLowerCase();
|
|
2226
|
+
// Handle .tsx and .jsx correctly
|
|
2227
|
+
if (ext === 'tsx')
|
|
2228
|
+
return 'tsx';
|
|
2229
|
+
if (ext === 'jsx')
|
|
2230
|
+
return 'jsx';
|
|
2231
|
+
if (ext === 'ts')
|
|
2232
|
+
return 'ts';
|
|
2233
|
+
if (ext === 'js')
|
|
2234
|
+
return 'js';
|
|
2235
|
+
if (ext === 'css')
|
|
2236
|
+
return 'css';
|
|
2237
|
+
if (ext === 'md')
|
|
2238
|
+
return 'md';
|
|
2239
|
+
if (ext === 'json')
|
|
2240
|
+
return 'json';
|
|
2241
|
+
if (ext === 'jsonc')
|
|
2242
|
+
return 'jsonc';
|
|
2243
|
+
throw new Error(`Unsupported file extension: .${ext}`);
|
|
2244
|
+
}
|
|
2245
|
+
export function evaluateFormula(raw, ctx, functions = SPREADSHEET_FUNCTIONS) {
|
|
2246
|
+
try {
|
|
2247
|
+
return evaluateAst(parseFormula(raw), ctx, functions);
|
|
2248
|
+
}
|
|
2249
|
+
catch {
|
|
2250
|
+
return "#ERROR!";
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
2253
|
+
export function isGraph(value) {
|
|
2254
|
+
return !!value &&
|
|
2255
|
+
typeof value === "object" &&
|
|
2256
|
+
value.cells instanceof Map &&
|
|
2257
|
+
value.computed instanceof Map &&
|
|
2258
|
+
value.deps instanceof Map &&
|
|
2259
|
+
value.dependents instanceof Map;
|
|
2260
|
+
}
|
|
2261
|
+
export function readGraphCell(graph, ref) {
|
|
2262
|
+
const key = normalizeCellRef(ref);
|
|
2263
|
+
return graph.computed.has(key)
|
|
2264
|
+
? graph.computed.get(key)
|
|
2265
|
+
: graph.cells.get(key)?.raw ?? 0;
|
|
2266
|
+
}
|
|
2267
|
+
export function readGraphRange(graph, ref) {
|
|
2268
|
+
const parsed = parseRangeStr(ref);
|
|
2269
|
+
if (!parsed) {
|
|
2270
|
+
return [[readGraphCell(graph, ref)]];
|
|
2271
|
+
}
|
|
2272
|
+
const startCol = colToIndex(parsed.start.col);
|
|
2273
|
+
const endCol = colToIndex(parsed.end.col);
|
|
2274
|
+
const minCol = Math.min(startCol, endCol);
|
|
2275
|
+
const maxCol = Math.max(startCol, endCol);
|
|
2276
|
+
const minRow = Math.min(parsed.start.row, parsed.end.row);
|
|
2277
|
+
const maxRow = Math.max(parsed.start.row, parsed.end.row);
|
|
2278
|
+
const rows = [];
|
|
2279
|
+
for (let row = minRow; row <= maxRow; row++) {
|
|
2280
|
+
const values = [];
|
|
2281
|
+
for (let col = minCol; col <= maxCol; col++) {
|
|
2282
|
+
const address = `${indexToCol(col)}${row}`;
|
|
2283
|
+
values.push(readGraphCell(graph, parsed.sheet
|
|
2284
|
+
? `${parsed.sheet}!${address}`
|
|
2285
|
+
: address));
|
|
2286
|
+
}
|
|
2287
|
+
rows.push(values);
|
|
2288
|
+
}
|
|
2289
|
+
return rows;
|
|
2290
|
+
}
|
|
2291
|
+
export function qualifyAst(node, sheet) {
|
|
2292
|
+
if (!sheet)
|
|
2293
|
+
return node;
|
|
2294
|
+
switch (node.type) {
|
|
2295
|
+
case "CellRef":
|
|
2296
|
+
case "Range":
|
|
2297
|
+
case "ColRange":
|
|
2298
|
+
return node.sheet ? node : { ...node, sheet };
|
|
2299
|
+
case "BinOp":
|
|
2300
|
+
return { ...node, left: qualifyAst(node.left, sheet), right: qualifyAst(node.right, sheet) };
|
|
2301
|
+
case "UnaryOp":
|
|
2302
|
+
return { ...node, operand: qualifyAst(node.operand, sheet) };
|
|
2303
|
+
case "FunctionCall":
|
|
2304
|
+
return { ...node, args: node.args.map(a => qualifyAst(a, sheet)) };
|
|
2305
|
+
case "ArrayLiteral":
|
|
2306
|
+
return { ...node, rows: node.rows.map(r => r.map(i => qualifyAst(i, sheet))) };
|
|
2307
|
+
default:
|
|
2308
|
+
return node;
|
|
2309
|
+
}
|
|
2310
|
+
}
|
|
2311
|
+
const visible = (g, key) => g.computed.get(key) ?? g.cells.get(key)?.raw;
|
|
2312
|
+
export function evaluateCell(graph, key) {
|
|
2313
|
+
const cell = graph.cells.get(key);
|
|
2314
|
+
if (!cell || !isFormula(cell.raw)) {
|
|
2315
|
+
graph.computed.delete(key);
|
|
2316
|
+
if (cell)
|
|
2317
|
+
delete cell.computed;
|
|
2318
|
+
return;
|
|
2319
|
+
}
|
|
2320
|
+
let result;
|
|
2321
|
+
try {
|
|
2322
|
+
result = cell.ast ? evaluateSpreadsheetAst(cell.ast, graph, key) : "#ERROR!";
|
|
2323
|
+
}
|
|
2324
|
+
catch {
|
|
2325
|
+
result = "#ERROR!";
|
|
2326
|
+
}
|
|
2327
|
+
// normalize function-returned { error } objects to the string convention
|
|
2328
|
+
if (isErr(result))
|
|
2329
|
+
result = result.error;
|
|
2330
|
+
if (isLambda(result))
|
|
2331
|
+
result = "#CALC!";
|
|
2332
|
+
cell.computed = result;
|
|
2333
|
+
graph.computed.set(key, result);
|
|
2334
|
+
}
|
|
2335
|
+
export function writeGraphCellInPlace(graph, address, raw, defaultSheet, volatileKeys = []) {
|
|
2336
|
+
const key = normalizeCellRef(address, defaultSheet);
|
|
2337
|
+
stageCell(graph, key, raw, defaultSheet);
|
|
2338
|
+
return recalculateDirty(graph, [key, ...volatileKeys], [key]);
|
|
2339
|
+
}
|
|
2340
|
+
export function clearGraphCellInPlace(graph, address, defaultSheet, volatileKeys = []) {
|
|
2341
|
+
const key = normalizeCellRef(address, defaultSheet);
|
|
2342
|
+
removeDependencies(graph, key);
|
|
2343
|
+
graph.cells.delete(key);
|
|
2344
|
+
graph.computed.delete(key);
|
|
2345
|
+
return recalculateDirty(graph, [key, ...volatileKeys], [key]);
|
|
2346
|
+
}
|
|
2347
|
+
export function writeGraphCellsInPlace(graph, edits, defaultSheet) {
|
|
2348
|
+
// normalize everything first so a bad address can't leave a half-applied batch
|
|
2349
|
+
const staged = [...edits].map(([addr, raw]) => [normalizeCellRef(addr, defaultSheet), raw]);
|
|
2350
|
+
for (const [key, raw] of staged)
|
|
2351
|
+
stageCell(graph, key, raw, defaultSheet);
|
|
2352
|
+
return recalculateDirty(graph, staged.map(([key]) => key)); // ONE recalc for the batch
|
|
2353
|
+
}
|
|
2354
|
+
export function writeGraphCell(graph, address, raw, defaultSheet) {
|
|
2355
|
+
const next = cloneGraph(graph);
|
|
2356
|
+
writeGraphCellInPlace(next, address, raw, defaultSheet);
|
|
2357
|
+
return next;
|
|
2358
|
+
}
|
|
2359
|
+
export function writeGraphCells(graph, edits, defaultSheet) {
|
|
2360
|
+
const next = cloneGraph(graph);
|
|
2361
|
+
writeGraphCellsInPlace(next, edits, defaultSheet);
|
|
2362
|
+
return next;
|
|
2363
|
+
}
|
|
2364
|
+
export function clearGraphCell(graph, address, defaultSheet) {
|
|
2365
|
+
const next = cloneGraph(graph);
|
|
2366
|
+
clearGraphCellInPlace(next, address, defaultSheet);
|
|
2367
|
+
return next;
|
|
2368
|
+
}
|
|
2369
|
+
const ERR_RE = /^#(NULL!|DIV\/0!|VALUE!|REF!|NAME\?|NUM!|N\/A|ERROR!|CYCLE!|CALC!|SPILL!)/;
|
|
2370
|
+
export function errCode(v) {
|
|
2371
|
+
if (typeof v === "string")
|
|
2372
|
+
return ERR_RE.test(v) ? v : undefined;
|
|
2373
|
+
if (typeof v === "object" && v !== null && "error" in v)
|
|
2374
|
+
return String(v.error);
|
|
2375
|
+
return undefined;
|
|
2376
|
+
}
|
|
2377
|
+
export function isEr1(v) { return errCode(v) !== undefined; }
|
|
2378
|
+
export function isErr(value) {
|
|
2379
|
+
return typeof value === "object" && value !== null && "error" in value;
|
|
2380
|
+
}
|
|
2381
|
+
export function isSpreadsheetError(v) { return typeof v === "string" && ERR_RE.test(v); }
|
|
2382
|
+
const normalizeResult = (v) => {
|
|
2383
|
+
if (typeof v === "number" && !Number.isFinite(v))
|
|
2384
|
+
return "#NUM!";
|
|
2385
|
+
if (typeof v === "object" && v !== null && "error" in v)
|
|
2386
|
+
return String(v.error);
|
|
2387
|
+
return v;
|
|
2388
|
+
};
|
|
2389
|
+
export function evaluateAst(node, ctx, functions = SPREADSHEET_FUNCTIONS) {
|
|
2390
|
+
const ev = (n, c = ctx) => evaluateAst(n, c, functions);
|
|
2391
|
+
switch (node.type) {
|
|
2392
|
+
case "Number":
|
|
2393
|
+
case "String":
|
|
2394
|
+
case "Boolean": return node.value;
|
|
2395
|
+
case "ErrorLiteral": return node.value;
|
|
2396
|
+
case "CellRef": return resolveCell(cellKey(node.col, node.row, node.sheet), ctx);
|
|
2397
|
+
case "Range": return expandRange(node, ctx);
|
|
2398
|
+
case "ColRange": {
|
|
2399
|
+
const sheet = node.sheet ?? ctx.sheet;
|
|
2400
|
+
const last = ctx.extent?.(sheet) ?? 0;
|
|
2401
|
+
if (last < 1)
|
|
2402
|
+
return [[0]];
|
|
2403
|
+
return expandRange({ sheet, start: { col: node.start, row: 1 }, end: { col: node.end, row: last } }, ctx);
|
|
2404
|
+
}
|
|
2405
|
+
case "StructuredRef": return "#REF!";
|
|
2406
|
+
case "Name": {
|
|
2407
|
+
const key = node.name.toUpperCase();
|
|
2408
|
+
if (ctx.scope?.has(key))
|
|
2409
|
+
return ctx.scope.get(key);
|
|
2410
|
+
if (functions[key])
|
|
2411
|
+
return { lambda: true, native: functions[key] }; // BYROW(A1:B3, SUM)
|
|
2412
|
+
return "#NAME?";
|
|
2413
|
+
}
|
|
2414
|
+
case "ArrayLiteral": return node.rows.map(row => row.map(item => ev(item)));
|
|
2415
|
+
case "UnaryOp": return evaluateUnary(node.op, ev(node.operand));
|
|
2416
|
+
case "BinOp": return evaluateBinary(node.op, ev(node.left), ev(node.right));
|
|
2417
|
+
case "FunctionCall": {
|
|
2418
|
+
try {
|
|
2419
|
+
const special = SPECIAL_FORMS[node.name];
|
|
2420
|
+
if (special)
|
|
2421
|
+
return normalizeResult(special(node.args, ctx, ev));
|
|
2422
|
+
const fn = functions[node.name];
|
|
2423
|
+
if (!fn)
|
|
2424
|
+
return "#NAME?";
|
|
2425
|
+
return normalizeResult(fn(node.args.map(a => ev(a)), ctx));
|
|
2426
|
+
}
|
|
2427
|
+
catch {
|
|
2428
|
+
return "#ERROR!";
|
|
2429
|
+
}
|
|
2430
|
+
}
|
|
2431
|
+
default: return "#ERROR!";
|
|
2432
|
+
}
|
|
2433
|
+
}
|
|
2434
|
+
export function collectDependencies(node, defaultSheet, output = new Set()) {
|
|
2435
|
+
switch (node.type) {
|
|
2436
|
+
case "CellRef": {
|
|
2437
|
+
output.add(cellKey(node.col.toUpperCase(), node.row, node.sheet ?? defaultSheet));
|
|
2438
|
+
return output;
|
|
2439
|
+
}
|
|
2440
|
+
case "Range": {
|
|
2441
|
+
const start = colToIndex(node.start.col);
|
|
2442
|
+
const end = colToIndex(node.end.col);
|
|
2443
|
+
const minCol = Math.min(start, end);
|
|
2444
|
+
const maxCol = Math.max(start, end);
|
|
2445
|
+
const minRow = Math.min(node.start.row, node.end.row);
|
|
2446
|
+
const maxRow = Math.max(node.start.row, node.end.row);
|
|
2447
|
+
for (let row = minRow; row <= maxRow; row++) {
|
|
2448
|
+
for (let col = minCol; col <= maxCol; col++) {
|
|
2449
|
+
output.add(cellKey(indexToCol(col), row, node.sheet ?? defaultSheet));
|
|
2450
|
+
}
|
|
2451
|
+
}
|
|
2452
|
+
return output;
|
|
2453
|
+
}
|
|
2454
|
+
case "BinOp":
|
|
2455
|
+
collectDependencies(node.left, defaultSheet, output);
|
|
2456
|
+
collectDependencies(node.right, defaultSheet, output);
|
|
2457
|
+
return output;
|
|
2458
|
+
case "UnaryOp":
|
|
2459
|
+
collectDependencies(node.operand, defaultSheet, output);
|
|
2460
|
+
return output;
|
|
2461
|
+
case "FunctionCall":
|
|
2462
|
+
for (const arg of node.args) {
|
|
2463
|
+
collectDependencies(arg, defaultSheet, output);
|
|
2464
|
+
}
|
|
2465
|
+
return output;
|
|
2466
|
+
case "ArrayLiteral":
|
|
2467
|
+
for (const row of node.rows) {
|
|
2468
|
+
for (const item of row) {
|
|
2469
|
+
collectDependencies(item, defaultSheet, output);
|
|
2470
|
+
}
|
|
2471
|
+
}
|
|
2472
|
+
return output;
|
|
2473
|
+
default:
|
|
2474
|
+
return output;
|
|
2475
|
+
}
|
|
2476
|
+
}
|
|
2477
|
+
export const MAX_ROW = 1048576;
|
|
2478
|
+
// #endregion
|