@sheetxl/skills 0.0.0-stage → 0.8.0-beta.15
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/LICENSE.md +21 -0
- package/README.md +84 -2
- package/SKILL.md +398 -0
- package/package.json +31 -3
- package/references/analysis.md +532 -0
- package/references/charts.md +173 -0
- package/references/cli.md +287 -0
- package/references/embedding.md +74 -0
- package/references/financial-models.md +364 -0
- package/references/interactive.md +194 -0
- package/references/reading.md +708 -0
- package/references/scripting.md +198 -0
- package/references/sessions.md +225 -0
- package/references/setup.md +74 -0
- package/references/showcase.md +32 -0
- package/references/udf.md +400 -0
- package/references/vector.md +129 -0
- package/references/writing.md +368 -0
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: udf
|
|
3
|
+
description: "SheetXL formula and UDF authoring using @sheetxl/primitives — writing, registering, debugging, or reviewing any formula function, built-in or user-defined. The only import is @sheetxl/primitives. Triggers on: formula function, UDF, custom function, built-in, IRange, FormulaContext, FormulaError, @sheetxl/primitives, sparseBuilder, mask, choose, ScalarType, JSDoc, coercion, broadcast semantics."
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# UDF — Formula Function Authoring
|
|
7
|
+
|
|
8
|
+
> Part of the SheetXL skill suite. See the root `SKILL.md` for routing.
|
|
9
|
+
|
|
10
|
+
**In this file:** The only import · Registering a UDF · Core invariants · The
|
|
11
|
+
oracle is observable Excel behavior · Never assume scalar · Parameter types ·
|
|
12
|
+
`IRange`: the body of every function · `FormulaContext` · JSDoc annotations ·
|
|
13
|
+
Error handling · Return values · Coercion · Contributing built-ins
|
|
14
|
+
|
|
15
|
+
Formula functions — both built-ins and UDFs — are pure TypeScript functions exported
|
|
16
|
+
from a module. The engine reads type signatures and JSDoc to auto-generate coercion,
|
|
17
|
+
validation, and UI metadata. Built-ins and UDFs use identical API; there is no
|
|
18
|
+
privileged internal surface.
|
|
19
|
+
|
|
20
|
+
## The Only Import
|
|
21
|
+
|
|
22
|
+
```typescript
|
|
23
|
+
import {
|
|
24
|
+
FormulaError, FormulaContext, ScalarType,
|
|
25
|
+
type Scalar, type IRange, type IReferenceRange
|
|
26
|
+
} from '@sheetxl/primitives';
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
`@sheetxl/primitives` is the complete authoring surface — the exclusive import for
|
|
30
|
+
formula functions. Any other import, including `@sheetxl/sdk`, is treated as a
|
|
31
|
+
third-party dependency bundled outside the formula sandbox. For method-level
|
|
32
|
+
detail, read the package's shipped types (`IRange`, `IFormulaContext`,
|
|
33
|
+
`FormulaError`, `ScalarType`) — as everywhere in SheetXL, the type definitions
|
|
34
|
+
are the authoritative reference.
|
|
35
|
+
|
|
36
|
+
---
|
|
37
|
+
|
|
38
|
+
## Registering a UDF
|
|
39
|
+
|
|
40
|
+
Functions register against a workbook's calculation engine. From `run` code
|
|
41
|
+
(either transport), use the function collection — pass the function source, JSDoc
|
|
42
|
+
included, as a string:
|
|
43
|
+
|
|
44
|
+
```typescript
|
|
45
|
+
const functions = wb.getCalculation().getFunctions();
|
|
46
|
+
functions.add(`
|
|
47
|
+
/**
|
|
48
|
+
* Returns the value doubled.
|
|
49
|
+
*/
|
|
50
|
+
export function DOUBLE(x: number): number { return x * 2; }
|
|
51
|
+
`);
|
|
52
|
+
wb.getWorksheet().evaluate('=DOUBLE(21)') // 42
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
In application code, providers can also be passed at construction
|
|
56
|
+
(`new Workbook({ functions: [...] })`) — see `embedding.md`. Either way the
|
|
57
|
+
authoring rules below are identical.
|
|
58
|
+
|
|
59
|
+
---
|
|
60
|
+
|
|
61
|
+
## Core Invariants
|
|
62
|
+
|
|
63
|
+
- Pure functions. No side effects, no global mutation.
|
|
64
|
+
- `IRange` is immutable. All methods return a new range, never mutate.
|
|
65
|
+
- `export function` declarations only. One function per export.
|
|
66
|
+
- Engine handles auto-boxing, broadcasting, and coercion. Do not reimplement them.
|
|
67
|
+
|
|
68
|
+
---
|
|
69
|
+
|
|
70
|
+
## The Oracle is Observable Excel Behavior
|
|
71
|
+
|
|
72
|
+
Excel compatibility is non-negotiable. Every function must match Excel's output exactly.
|
|
73
|
+
|
|
74
|
+
The published spec documents Excel's intended behavior but is incomplete by design —
|
|
75
|
+
it omits edge cases, implicit broadcast rules, type coercion behavior, and sorting
|
|
76
|
+
semantics that Excel implements but never formally specifies. The only authoritative
|
|
77
|
+
source is what Excel actually does. When spec and observation diverge, observation
|
|
78
|
+
wins. When the spec is silent, observation is the only guide.
|
|
79
|
+
|
|
80
|
+
Practical rule: test in Excel directly. Trust the empirical result over documentation,
|
|
81
|
+
including Microsoft's own.
|
|
82
|
+
|
|
83
|
+
---
|
|
84
|
+
|
|
85
|
+
## The Golden Rule: Never Assume Scalar
|
|
86
|
+
|
|
87
|
+
In modern Excel, functions that appear to take scalar arguments are implicitly lifted
|
|
88
|
+
(auto-broadcast) to support range/array inputs with full broadcast semantics.
|
|
89
|
+
|
|
90
|
+
Known cases that have caused incorrect implementations in other engines:
|
|
91
|
+
|
|
92
|
+
- `CHOOSE(index, ...)` — index accepts a range
|
|
93
|
+
- `SWITCH(expr, ...)` — expr accepts a range
|
|
94
|
+
- `IF(condition, ...)` — condition is a range in array context
|
|
95
|
+
- `IFS(cond1, val1, ...)` — all conditions and values accept ranges
|
|
96
|
+
|
|
97
|
+
---
|
|
98
|
+
|
|
99
|
+
## Parameter Types
|
|
100
|
+
|
|
101
|
+
### Scalar
|
|
102
|
+
|
|
103
|
+
```typescript
|
|
104
|
+
export function ADD(a: number, b: number): number { return a + b; }
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
The engine auto-coerces and auto-broadcasts. A scalar parameter can receive a range
|
|
108
|
+
at the call site; the engine handles the broadcast. Do not implement manual broadcasting.
|
|
109
|
+
|
|
110
|
+
### IRange<T>
|
|
111
|
+
|
|
112
|
+
Declare the type in the generic: `IRange<number>`, `IRange<string>`, `IRange<Scalar>`.
|
|
113
|
+
Coercion is handled automatically. Use `ValueOptions` only when default coercion
|
|
114
|
+
is insufficient. The operations themselves are in [vector](vector.md).
|
|
115
|
+
|
|
116
|
+
### Optional and default parameters
|
|
117
|
+
|
|
118
|
+
```typescript
|
|
119
|
+
export function ROUND(number: number, numDigits?: number): number { ... }
|
|
120
|
+
export function LOG(number: number, base: number = 10): number { ... }
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
### Variadic (1-N ranges)
|
|
124
|
+
|
|
125
|
+
```typescript
|
|
126
|
+
export function MAX(...number: IRange<number>[]): number { ... }
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### Enum (a closed set of values)
|
|
130
|
+
|
|
131
|
+
Declare a plain TypeScript `enum` in the SAME file and type the parameter with it. Doc comment
|
|
132
|
+
every member on its own line; the doc is the help a user sees when picking the value.
|
|
133
|
+
|
|
134
|
+
```typescript
|
|
135
|
+
/** When payments are due in each period. */
|
|
136
|
+
enum PaymentType {
|
|
137
|
+
/**
|
|
138
|
+
* Payments are due at the end of each period.
|
|
139
|
+
* @name At the end of the period
|
|
140
|
+
*/
|
|
141
|
+
End = 0,
|
|
142
|
+
/** Payments are due at the beginning of each period. */
|
|
143
|
+
Beginning = 1,
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function FV(rate: number, nper: number, pmt: number, pv: number = 0,
|
|
147
|
+
type: PaymentType = PaymentType.End): number { ... }
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
- **It gates.** The body only ever receives a member. A value outside the set (`2`, and also `0.5`:
|
|
151
|
+
no truncation) is `#VALUE!` and the body does not run; under a lift, just that element is.
|
|
152
|
+
- **Strings are case-insensitive.** A string enum delivers the DECLARED spelling (`"MERCURY"` → `'mercury'`).
|
|
153
|
+
- **`ReportType<E>` opts out of the gate.** The value arrives unchecked and the body decides. Use it
|
|
154
|
+
when Excel's own rule is not "exactly a member": the built-ins that truncate, read any nonzero as
|
|
155
|
+
1, or answer `#NUM!` are all declared this way.
|
|
156
|
+
- **`E | Scalar` documents the values of an uncoerced slot.** The body receives the raw argument,
|
|
157
|
+
whatever it is, and reads it itself; the enum only drives the dropdown, the help and the editor's
|
|
158
|
+
warning. Use it when a slot takes more than the set (`WORKDAY.INTL`'s weekend is a code OR a
|
|
159
|
+
`"0000011"` mask).
|
|
160
|
+
- **`@name` sets the label** the editor shows for the value, and works on the enum too, just as it
|
|
161
|
+
does on a function. Without it the label is the member's name pretty-printed (`MemAvail` →
|
|
162
|
+
"Mem Avail", `OSVersion` → "OS Version").
|
|
163
|
+
- **`@deprecated` on a member keeps it out of the dropdown.** It stays in the set, so a formula that
|
|
164
|
+
names it is not refused and the body decides what it answers. Use it for a value Excel defines that
|
|
165
|
+
the function does not compute (`CELL`'s `"width"`); the tag's text says why.
|
|
166
|
+
- **Also accepted:** an `as const` object with a same-name type alias, and a bare literal union
|
|
167
|
+
(`mode: 0 | 1`, which shows the raw values with no labels). Numbers or strings, never mixed; the
|
|
168
|
+
set need not be contiguous (`-1 | 0 | 1`).
|
|
169
|
+
- **Composes with the markers:** `Omittable<E, V>` (`V` must be a member or `null`), `AcceptError<E>`,
|
|
170
|
+
`NoLift<E>`, `...values: E[]`. It is REFUSED under `IRange<E>`, `Flatten<E>`, `E[][]` and
|
|
171
|
+
`Lazy<E>`: a range's members are never coerced one argument at a time.
|
|
172
|
+
- **`IRange<ReportType<E>>` documents a range's members.** Nothing is checked, and the body reads the
|
|
173
|
+
range itself; the enum drives the dropdown, the help and the warning (`SORT`'s `sort_order`, one
|
|
174
|
+
order per key). It is not `ReportType<IRange>`, which is about how a multi-area reference arrives.
|
|
175
|
+
- **Not imported.** An enum from another file is invisible to the compiler (SXL2052).
|
|
176
|
+
|
|
177
|
+
In the formula editor and the Function Arguments dialog, an empty argument of an enum type offers
|
|
178
|
+
its members as a dropdown, each row its label then its value; choosing one inserts the value. Any
|
|
179
|
+
other text is still accepted. A literal outside the set is
|
|
180
|
+
underlined as a warning in the editor, and never refused there.
|
|
181
|
+
|
|
182
|
+
### IReferenceRange
|
|
183
|
+
|
|
184
|
+
Use only when the function returns or requires a live cell reference (`INDIRECT`,
|
|
185
|
+
`OFFSET`). This registers a dynamic precedent in the dependency graph. Most functions
|
|
186
|
+
that look like they need this do not.
|
|
187
|
+
|
|
188
|
+
---
|
|
189
|
+
|
|
190
|
+
## IRange: the body of every function
|
|
191
|
+
|
|
192
|
+
Formula functions are pure transformations: `IRange -> IRange`. `ICellRange` is the
|
|
193
|
+
mutable sheet-level API used by the UI and `run` code — do not use it in formulas.
|
|
194
|
+
|
|
195
|
+
**The `IRange` surface itself lives in [vector](vector.md)** — iteration with
|
|
196
|
+
`entries()`, building output with `sparseBuilder()`, the `mask`/`choose`/`select`
|
|
197
|
+
dispatch primitives, shape and coercion. Load it before writing a function body;
|
|
198
|
+
everything there applies unchanged here, because a function body *is* vector code.
|
|
199
|
+
|
|
200
|
+
Two things are specific to formulas rather than to `IRange`:
|
|
201
|
+
|
|
202
|
+
- Arguments arrive as `IRange` already and the return value is one — there is no
|
|
203
|
+
`getValuesRange()` bridge inside a function, and no `ICellRange` in scope.
|
|
204
|
+
- `FormulaContext.createRange()` is how you make a new range to return as a
|
|
205
|
+
dynamic-array result (below).
|
|
206
|
+
|
|
207
|
+
---
|
|
208
|
+
|
|
209
|
+
## FormulaContext
|
|
210
|
+
|
|
211
|
+
`FormulaContext` is the sandboxed gateway from a formula function to the calculation
|
|
212
|
+
runtime. Import it from `@sheetxl/primitives` and call its static methods directly —
|
|
213
|
+
no instantiation, no passing it around. The engine configures it automatically before
|
|
214
|
+
each function call so every method is already scoped to the evaluating function's cell
|
|
215
|
+
and sheet.
|
|
216
|
+
|
|
217
|
+
This is the **only** way a function should access the host runtime. Reaching outside
|
|
218
|
+
(e.g. via `@sheetxl/sdk` imports or global state) is not supported and breaks the
|
|
219
|
+
sandbox contract.
|
|
220
|
+
|
|
221
|
+
```typescript
|
|
222
|
+
import { FormulaContext } from '@sheetxl/primitives';
|
|
223
|
+
|
|
224
|
+
export function NOW(): number {
|
|
225
|
+
FormulaContext.markVolatile();
|
|
226
|
+
FormulaContext.formatResults('Short DateTime');
|
|
227
|
+
return FormulaContext.getNow(); // deterministic, session-scoped time
|
|
228
|
+
}
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
### Method reference
|
|
232
|
+
|
|
233
|
+
| Method | Purpose |
|
|
234
|
+
|---|---|
|
|
235
|
+
| `FormulaContext.markVolatile()` | Recalculate every cycle: `RAND`, `NOW`, `TODAY` |
|
|
236
|
+
| `FormulaContext.getNow()` | Current time as a serial date — deterministic and session-scoped. Never call `Date.now()` directly |
|
|
237
|
+
| `FormulaContext.getRandom()` | A draw in `[0, 1)` — the runtime's source, which a host can seed (a seeded draw is keyed by cell and pass, so take draws where they are used). Never call `Math.random()` directly |
|
|
238
|
+
| `FormulaContext.getEntireCoords()` | Destination cell bounds for array functions (e.g. `SEQUENCE`) |
|
|
239
|
+
| `FormulaContext.formatResults(numFmt)` | Hint engine to apply number format to result cell |
|
|
240
|
+
| `FormulaContext.getFunction(name)` | Call another registered function by name |
|
|
241
|
+
| `FormulaContext.createRange()` | Create a new `IRange` to return as a dynamic array result |
|
|
242
|
+
| `FormulaContext.getReference(coords)` | Resolve a dynamic range reference (adds a tracked dependency) |
|
|
243
|
+
| `FormulaContext.toSerialDate(date)` / `fromSerialDate(n)` | Convert between JS `Date` and Excel serial numbers |
|
|
244
|
+
| `FormulaContext.parseAsDate(v)` / `parseAsSerialDate(v)` | Parse a scalar (string or number) into a date |
|
|
245
|
+
| `FormulaContext.parseAsNumber(v)` | Parse a scalar into a number |
|
|
246
|
+
| `FormulaContext.filterHidden(range)` | Strip hidden rows/columns (used by `SUBTOTAL`, `AGGREGATE`) |
|
|
247
|
+
| `FormulaContext.getRow()` / `getColumn()` | 0-based coords of the cell being evaluated |
|
|
248
|
+
|
|
249
|
+
---
|
|
250
|
+
|
|
251
|
+
## JSDoc Annotations (Required)
|
|
252
|
+
|
|
253
|
+
The comment text above the tags is the function's description: it is shown in the formula dropdown and tooltips. A function without one gets a warning.
|
|
254
|
+
|
|
255
|
+
| Tag | Notes |
|
|
256
|
+
|---|---|
|
|
257
|
+
| `@param <n>` | Should match parameter names exactly — mismatches produce a warning. |
|
|
258
|
+
| `@name` | Required when the Excel function name contains symbols invalid in TypeScript (e.g. `.` in `CEILING.MATH`, `PERCENTILE.INC`). Maps the export name to the Excel name. |
|
|
259
|
+
| `@category` | UI grouping. Defaults to `Custom`. UDFs can use any category name, including the built-in ones. |
|
|
260
|
+
| `@description` | Long description for the detail panel. |
|
|
261
|
+
| `@hidden` | Hides from UI but remains available to the calc engine. Always include a reason string. |
|
|
262
|
+
|
|
263
|
+
```typescript
|
|
264
|
+
/**
|
|
265
|
+
* Returns a number rounded up to the nearest integer or multiple of significance.
|
|
266
|
+
* @name CEILING.MATH
|
|
267
|
+
*/
|
|
268
|
+
export function CEILING_MATH(number: number, significance?: number, mode: number = 0): number { ... }
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
---
|
|
272
|
+
|
|
273
|
+
## Error Handling
|
|
274
|
+
|
|
275
|
+
Prefer `return` for propagated errors (faster). Use `throw` to abort immediately.
|
|
276
|
+
|
|
277
|
+
```typescript
|
|
278
|
+
if (FormulaError.isError(v)) return v; // propagate
|
|
279
|
+
return FormulaError.BuiltIn.Value; // #VALUE!
|
|
280
|
+
return FormulaError.BuiltIn.NA; // #N/A
|
|
281
|
+
return FormulaError.BuiltIn.Div0; // #DIV/0!
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
Automatic JS-to-error mappings:
|
|
285
|
+
|
|
286
|
+
| Return value | Becomes |
|
|
287
|
+
|---|---|
|
|
288
|
+
| `Number.NaN` | `#NUM!` |
|
|
289
|
+
| `Infinity` / `-Infinity` | `#NUM!` |
|
|
290
|
+
| `undefined` | `#VALUE!` |
|
|
291
|
+
|
|
292
|
+
### Write plain arithmetic — but say `#DIV/0!` out loud
|
|
293
|
+
|
|
294
|
+
The engine normalizes every result the way Excel does: a non-finite becomes `#NUM!`, and a
|
|
295
|
+
magnitude below the smallest normal double flushes to `0`. So ordinary JavaScript is already
|
|
296
|
+
correct for overflow and underflow, and a function body should not check for them.
|
|
297
|
+
|
|
298
|
+
```typescript
|
|
299
|
+
export function SQUARE(x: number): number { return x * x; } // 9E+307 -> #NUM!, free
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
`#DIV/0!` is the one error that does **not** fall out of the arithmetic. Excel never derives it
|
|
303
|
+
from a float — it raises it deliberately before dividing — and in JavaScript `x / 0` is the same
|
|
304
|
+
`Infinity` an overflow produces, which the rule above reports as `#NUM!`. A function that can
|
|
305
|
+
divide by zero has to say so:
|
|
306
|
+
|
|
307
|
+
```typescript
|
|
308
|
+
export function RATIO(a: number, b: number): number {
|
|
309
|
+
if (b === 0) return FormulaError.BuiltIn.Div0; // WITHOUT this, RATIO(1, 0) is #NUM!
|
|
310
|
+
return a / b;
|
|
311
|
+
}
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
The same applies to any implicit division — `1 / Math.sin(0)`, `Math.log(x) / Math.log(1)`,
|
|
315
|
+
a mean over an empty sample. If Excel answers `#DIV/0!` for the degenerate input, guard it.
|
|
316
|
+
|
|
317
|
+
Never hand back a raw `Infinity` to mean `#DIV/0!`; it means `#NUM!`.
|
|
318
|
+
|
|
319
|
+
---
|
|
320
|
+
|
|
321
|
+
## Return Values
|
|
322
|
+
|
|
323
|
+
| Return type | Spill behavior |
|
|
324
|
+
|---|---|
|
|
325
|
+
| `Scalar` | Single cell |
|
|
326
|
+
| `Scalar[]` | Spills as a single row |
|
|
327
|
+
| `Scalar[][]` | Spills as a 2D block (outer array = rows) |
|
|
328
|
+
| `IRange` | Spills; preferred for large or sparse results |
|
|
329
|
+
|
|
330
|
+
---
|
|
331
|
+
|
|
332
|
+
## Coercion
|
|
333
|
+
|
|
334
|
+
| Source | Aggregation fns (SUM, AVERAGE...) | Non-aggregation fns (ROUND, etc.) |
|
|
335
|
+
|---|---|---|
|
|
336
|
+
| Cell reference | Boolean skipped | Boolean coerced |
|
|
337
|
+
| Literal scalar arg | Coerced | Coerced |
|
|
338
|
+
| Literal array `{TRUE}` | Skipped | Skipped silently |
|
|
339
|
+
|
|
340
|
+
Empirically verified — verify any new aggregation against all of these:
|
|
341
|
+
|
|
342
|
+
- `=AVERAGE(1, TRUE)` -> `0.667` (literal scalar TRUE coerces)
|
|
343
|
+
- `=AVERAGE(A1, B1)` (B1=TRUE) -> `1.0` (cell-ref boolean skipped)
|
|
344
|
+
- `=AVERAGE(1, {TRUE})` -> `0.5` (array boolean skipped)
|
|
345
|
+
- `=AVERAGE(1, "TRUE")` -> `#VALUE!` (string literal errors)
|
|
346
|
+
|
|
347
|
+
---
|
|
348
|
+
|
|
349
|
+
## Contributing built-ins (SheetXL repo only)
|
|
350
|
+
|
|
351
|
+
This section applies when working **inside the SheetXL repository** on the shipped
|
|
352
|
+
function set — not when authoring a UDF in your own project.
|
|
353
|
+
|
|
354
|
+
- Built-ins live in `packages/formulas` (`@sheetxl/formulas`). The signature
|
|
355
|
+
determines the test cases; the implementation can be reviewed for edge cases,
|
|
356
|
+
but Excel behavior — not the SheetXL implementation — is the oracle.
|
|
357
|
+
- Every implementation requires a fixture file, manually validated against Excel:
|
|
358
|
+
|
|
359
|
+
```text
|
|
360
|
+
packages/sdk/src/__tests__/functions/<category>/<FUNCTIONNAME>.json
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
(Categories: `mathTrig`, `statistical`, `financial`, `text`, `logical`,
|
|
364
|
+
`lookupReference`, `engineering`, `information`, `database`, `operators`.
|
|
365
|
+
Closely related functions may share one file, e.g. `CEILING-FLOOR.json`.)
|
|
366
|
+
|
|
367
|
+
**Simple** — all arguments are literals:
|
|
368
|
+
|
|
369
|
+
```json
|
|
370
|
+
[{
|
|
371
|
+
"label": "DISC",
|
|
372
|
+
"simple": {
|
|
373
|
+
"DISC(\"01/04/2023\", \"01/31/2023\", 99.71275, 100, 0)": 0.0383,
|
|
374
|
+
"DISC(\"01/04/2023\", \"01/31/2023\", 99.71275, 100, -1)": "#NUM!"
|
|
375
|
+
}
|
|
376
|
+
}]
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
**Detailed** — formula references cell addresses:
|
|
380
|
+
|
|
381
|
+
```json
|
|
382
|
+
[{
|
|
383
|
+
"label": "single criterion",
|
|
384
|
+
"formula": "COUNTIF(A1:A4, \">2\")",
|
|
385
|
+
"inputs": {
|
|
386
|
+
"A1": [
|
|
387
|
+
[1],
|
|
388
|
+
[2],
|
|
389
|
+
[3],
|
|
390
|
+
[4]
|
|
391
|
+
]
|
|
392
|
+
},
|
|
393
|
+
"expect": 2
|
|
394
|
+
}]
|
|
395
|
+
```
|
|
396
|
+
|
|
397
|
+
Every fixture must cover: happy path, each non-default optional argument, error
|
|
398
|
+
propagation and error conditions, coercion edge cases (text, string, boolean),
|
|
399
|
+
implicit lifting for scalar parameters, broadcast/spill cases, literal **and**
|
|
400
|
+
referenced inputs, and at least one non-A1 origin address (detailed fixtures only).
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: vector
|
|
3
|
+
description: "The IRange vector surface — SheetXL's NumPy-shaped array API for computing over many cells without materializing them. Iteration with entries(), building output with sparseBuilder(), dispatch with mask/choose/select, shape and coercion, and the read/write bridges getValuesRange() and setComputedValues(). Load when transforming a column, filtering or sorting values, broadcasting an operation, or writing any formula-function body. Triggers on: IRange, getValuesRange, setComputedValues, entries, sparseBuilder, pushAt, mask, choose, select, tile, repeat, resize, getShape, getValueAt, fillEmpty, Axis, vector, columnar, sparse, broadcast, transform a column, compute without materializing, NumPy."
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Vector — `IRange`, the Compute Surface
|
|
7
|
+
|
|
8
|
+
> Part of the SheetXL skill suite. See the root `SKILL.md` for routing.
|
|
9
|
+
> For finding and profiling data, `reading.md`; for writing cells, `writing.md`;
|
|
10
|
+
> for authoring formula functions, `udf.md` (whose bodies are `IRange` code).
|
|
11
|
+
|
|
12
|
+
`IRange` is where computation happens. It is an immutable, two-dimensional,
|
|
13
|
+
mixed-type **sparse** array with functional vector semantics, shaped for
|
|
14
|
+
NumPy/JAX familiarity: every operation returns a new range through structural
|
|
15
|
+
sharing, so transforms are zero-copy and reads are SIMD-optimized. Sparse and
|
|
16
|
+
mixed types are the normal case here, not an edge case.
|
|
17
|
+
|
|
18
|
+
**This is the answer to "I need to loop over the values".** You almost never do.
|
|
19
|
+
|
|
20
|
+
## Getting in and out
|
|
21
|
+
|
|
22
|
+
| | |
|
|
23
|
+
|---|---|
|
|
24
|
+
| a cell range → a vector | `range.getValuesRange(): IRange` |
|
|
25
|
+
| a vector → back into the sheet | `range.setValues(vector)` |
|
|
26
|
+
| both at once | `range.setComputedValues(fn)` |
|
|
27
|
+
|
|
28
|
+
`setComputedValues(fn)` is exactly `setValues(fn(getValuesRange()))` — the range
|
|
29
|
+
goes in as an `IRange`, the transform runs in the engine, and the values never
|
|
30
|
+
round-trip through your runtime:
|
|
31
|
+
|
|
32
|
+
```typescript
|
|
33
|
+
wb.getRange('B2:B400').setComputedValues(src => /* IRange in, IRange out */);
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Inside a formula function there is no cell range at all: the arguments arrive as
|
|
37
|
+
`IRange` already, and the return value is one. Same vocabulary, no bridge.
|
|
38
|
+
|
|
39
|
+
## The five primitives
|
|
40
|
+
|
|
41
|
+
Everything else composes from these, and they are the ones worth knowing by name:
|
|
42
|
+
|
|
43
|
+
| | |
|
|
44
|
+
|---|---|
|
|
45
|
+
| `entries(options?)` | iterate — sparse or dense, by axis, by direction, coercible |
|
|
46
|
+
| `sparseBuilder()` | streaming writer for building sparse output |
|
|
47
|
+
| `getShape()` | `{ rows, columns }` |
|
|
48
|
+
| `resize()` | a new range at a different shape, with a fill value |
|
|
49
|
+
| `getType()` | the scalar type used for default coercion |
|
|
50
|
+
|
|
51
|
+
Optimised alongside them: `getValueAt(row, column)`, `fill()`, `fillEmpty()`,
|
|
52
|
+
`clone()`, `getStats()`. The rest of the utility surface — `mask`, `choose`,
|
|
53
|
+
`select`, `tile`, `repeat` and friends — composes from the five, and the NumPy
|
|
54
|
+
names mean what you expect. **The shipped types are the authority**; roughly 45
|
|
55
|
+
operations are there, and this file teaches the ones whose usage is not obvious
|
|
56
|
+
from a signature.
|
|
57
|
+
|
|
58
|
+
## Iteration — `entries()`
|
|
59
|
+
|
|
60
|
+
Use `entries()` for all traversal. **Column orientation is faster** — it aligns
|
|
61
|
+
with the internal columnar storage — so use it whenever row-major order is not
|
|
62
|
+
actually required.
|
|
63
|
+
|
|
64
|
+
```typescript
|
|
65
|
+
const iterEntries = array.entries({
|
|
66
|
+
axis: IRange.Axis.Column,
|
|
67
|
+
includeEmpty: false,
|
|
68
|
+
});
|
|
69
|
+
let iter = iterEntries.next();
|
|
70
|
+
while (!iter.done) {
|
|
71
|
+
const { value, coords } = iter.value;
|
|
72
|
+
const { rowIndex, colIndex } = coords;
|
|
73
|
+
iter = iterEntries.next();
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
`getValueAt(row, col)` is the **slowest** access pattern. Reserve it for O(1)
|
|
78
|
+
spot lookups; never build a loop out of it.
|
|
79
|
+
|
|
80
|
+
## Building output — `sparseBuilder()`
|
|
81
|
+
|
|
82
|
+
> `sparseBuilder()` is **additive** — it inherits the existing values of the range
|
|
83
|
+
> it is called on. To build fresh output, always call `empty().sparseBuilder()`.
|
|
84
|
+
> Calling `sparseBuilder()` directly is correct only when you are selectively
|
|
85
|
+
> overwriting values in an otherwise unchanged range.
|
|
86
|
+
|
|
87
|
+
```typescript
|
|
88
|
+
const builder = empty().sparseBuilder();
|
|
89
|
+
builder.pushAt(rowIndex, colIndex, value); // monotonically increasing coordinate order
|
|
90
|
+
const result: IRange = builder.build();
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
`pushAt` requires monotonically increasing coordinates. That constraint is what
|
|
94
|
+
makes the builder streaming rather than a sort.
|
|
95
|
+
|
|
96
|
+
## Dispatch primitives
|
|
97
|
+
|
|
98
|
+
Branching over a whole range is a primitive, not a loop with an `if` in it:
|
|
99
|
+
|
|
100
|
+
| Primitive | Use for |
|
|
101
|
+
|---|---|
|
|
102
|
+
| `mask` | Boolean dispatch — `IF` |
|
|
103
|
+
| `choose` | Index dispatch; `selectFn` returns a 0-based index into `ranges[]` — `CHOOSE`, `IFS` |
|
|
104
|
+
| `select` | Value-equality dispatch, matching an expression against `match[]` — `SWITCH` |
|
|
105
|
+
|
|
106
|
+
## Typing and coercion
|
|
107
|
+
|
|
108
|
+
Declare the element type in the generic: `IRange<number>`, `IRange<string>`,
|
|
109
|
+
`IRange<Scalar>`. Coercion is handled for you; reach for `ValueOptions` only when
|
|
110
|
+
the default coercion is insufficient.
|
|
111
|
+
|
|
112
|
+
`IRange` is **immutable** — every method returns a new range and none mutates.
|
|
113
|
+
This is what makes structural sharing safe, and it is why a "transform" is a
|
|
114
|
+
return value rather than an in-place edit.
|
|
115
|
+
|
|
116
|
+
## Choosing between the vector surface and stats
|
|
117
|
+
|
|
118
|
+
They answer different questions, and the wrong one is the expensive one:
|
|
119
|
+
|
|
120
|
+
| Question | Reach for |
|
|
121
|
+
|---|---|
|
|
122
|
+
| what are these values like — sum, min, distribution | `range.getStats()` (`reading.md`) |
|
|
123
|
+
| produce new values from these values | `IRange` |
|
|
124
|
+
| I need the values in JavaScript | `getValues()` — the exit door |
|
|
125
|
+
|
|
126
|
+
`getStats()` reduces in one pass and returns an answer. `IRange` transforms and
|
|
127
|
+
returns a range. Only `getValues()` copies the grid into your runtime, and it is
|
|
128
|
+
for handing data to something outside the engine — a file, another tool, the
|
|
129
|
+
user's eyes.
|