Skip to content

feat: implement UNIQUE dynamic array function (HF-68) - #1708

Merged
sequba merged 8 commits into
developfrom
feature/HF-68-unique
Jul 23, 2026
Merged

sequba merged 8 commits into
developfrom
feature/HF-68-unique

Conversation

@marcin-kordas-hoc

@marcin-kordas-hoc marcin-kordas-hoc commented Jul 13, 2026 •

Copy link
Copy Markdown
Collaborator

What & why

Implements UNIQUE (HF-68, child of HF-28 "Modern dynamic array functions", sibling of the shipped SEQUENCE and of VSTACK/HSTACK). Adds UNIQUE(array, [by_col], [exactly_once]) as a dynamic array function.

Tests: handsontable/hyperformula-tests#25 (paired).
Sibling PR: #1707 (SORT / HF-69).
ADR: docs/adr/2026-07-13-sort-unique-array-functions.md.

Behavior

  • Returns the distinct rows (or columns when by_col is TRUE) of the input, preserving first-occurrence order.
  • by_col: FALSE (default) compares rows; TRUE compares columns.
  • exactly_once: TRUE returns only rows/columns occurring exactly once; FALSE (default) returns all distinct.
  • Equality reuses ArithmeticHelper.eq → case-insensitive by default (honors caseSensitive), matching Excel's UNIQUE.
  • Result size is data-dependent; mirrors FILTER (predict input size as upper bound, return the smaller actual result).

Design

Mirrors the FILTER machinery for dynamic-size results: sizeOfResultArrayMethod + vectorizationForbidden: true, runtime via runFunction, parse-time size method returning a fresh ArraySize (drops the input's isRef flag). Deduplication is O(n²) in the number of vectors because locale-aware equality is not trivially hashable — noted in code; acceptable for v1.

Notes — divergences from Excel (surfaced here + inline + in tests)

  • Empty result (only via exactly_once when nothing occurs exactly once) → #N/A. Excel returns #CALC!, which HyperFormula has no type for; mirrors FILTER's empty-result mapping (ADR dec_8).
  • Comparison honors HF's collation config rather than a byte-for-byte Excel oracle (no live Excel in this environment; ADR con_1).
  • In-range errors propagate (first error found; ADR dec_7).

Definition of Done

  • Production code (UniquePlugin.ts, registered via plugin/index.ts)
  • i18n — all 17 language packs (authoritative MS Functions Translator names; enUS inherits enGB)
  • Tests (paired tests PR) — across the standard array-function groups, dual-env safe
  • Docs — built-in-functions.md, known-limitations.md
  • JSDoc on all methods
  • CHANGELOG entry
  • ADR with audit-verified citations

Source: https://app.clickup.com/t/86c89q1tq


Note

Low Risk
Additive array function behind existing dynamic-array machinery; no changes to auth, persistence, or core evaluation paths beyond new plugin registration.

Overview
Adds the Excel-style UNIQUE(array, [ByCol], [ExactlyOnce]) dynamic array function so formulas can return distinct rows or columns with first-occurrence order preserved.

UniquePlugin implements deduplication via ArithmeticHelper.eq (honors caseSensitive / accentSensitive), optional column-wise mode and “exactly once” filtering, propagates the first in-range error, and returns #N/A when ExactlyOnce would yield an empty result (aligned with FILTER). Spill sizing follows FILTER: parse-time upper bound from input dimensions, vectorizationForbidden: true, and a fresh ArraySize so isRef is not carried through.

Also registers the plugin, adds UNIQUE to all language packs, documents the function and known limitations, and records the change in the changelog.

Reviewed by Cursor Bugbot for commit a4097a4. Bugbot is set up for automated code reviews on this repo. Configure here.

@netlify

netlify Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for hyperformula-dev-docs ready!

Name Link
🔨 Latest commit a4097a4
🔍 Latest deploy log https://app.netlify.com/projects/hyperformula-dev-docs/deploys/6a621e940c32ca0008477d83
😎 Deploy Preview https://deploy-preview-1708--hyperformula-dev-docs.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@qunabu

qunabu commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

@github-actions

github-actions Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Performance comparison of head (a4097a4) vs base (fbb4710)

                                     testName |    base |    head |  change
---------------------------------------------------------------------------
                                      Sheet A |     495 |  507.56 |  +2.54%
                                      Sheet B |  160.29 |  162.17 |  +1.17%
                                      Sheet T |  143.45 |  141.76 |  -1.18%
                                Column ranges |  471.88 |  470.22 |  -0.35%
                                Sorted lookup | 14055.5 | 14161.3 |  +0.75%
Sheet A:  change value, add/remove row/column |   16.93 |   14.94 | -11.75%
 Sheet B: change value, add/remove row/column |  134.05 |  132.66 |  -1.04%
                   Column ranges - add column |  146.51 |  150.95 |  +3.03%
                Column ranges - without batch |  454.89 |  457.81 |  +0.64%
                        Column ranges - batch |  115.85 |  117.37 |  +1.31%

@marcin-kordas-hoc
marcin-kordas-hoc requested a review from sequba July 16, 2026 12:20
Add UNIQUE(array, [by_col], [exactly_once]) as a dynamic array function,
mirroring the FILTER machinery for data-dependent result size. Deduplication
preserves first-occurrence order and reuses ArithmeticHelper for equality
(case-insensitive by default, honoring the caseSensitive config). Supports
by_col (unique columns) and exactly_once (values occurring exactly once).
Errors in the input range propagate; an empty exactly_once result yields #N/A.

Includes i18n for all 17 language packs, docs (built-in-functions,
known-limitations), a changelog entry, and the shared ADR.

Source: https://app.clickup.com/t/86c89q1tq
ADR: docs/adr/2026-07-13-sort-unique-array-functions.md

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
marcin-kordas-hoc and others added 4 commits July 21, 2026 10:30
Without enableArrayArithmeticForArguments, an array expression passed as
the first argument (e.g. =UNIQUE(A1:A3*2)) is coerced as a scalar and only
the first cell is computed. Matches FILTER/VSTACK/HSTACK/SORT.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…s (HF-68)

The compared vectors are always rows (or columns, after transpose) of the
same rectangular range, so they never differ in length — the guard was dead
code. Removes the last uncovered line in UniquePlugin.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Per review on #1707: keep the ADR but relocate it out of the engine repo
into hyperformula-tests/dev_docs, since a per-function implementation ADR
belongs with the test suite rather than the shipped docs dir.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@marcin-kordas-hoc

Copy link
Copy Markdown
Collaborator Author

Moved the shared SORT/UNIQUE ADR out of the engine repo into hyperformula-tests/dev_docs/ per the discussion on #1707 — added to the paired tests PR handsontable/hyperformula-tests#25 and removed from this branch.

marcin-kordas-hoc and others added 2 commits July 23, 2026 12:29
Reword the known-limitations guide and the plugin JSDoc to describe HF's
own case-insensitive comparison instead of framing it as matching Excel,
keeping published surfaces free of the comparison claim. Internal code
comments referencing Excel as the behavioural oracle are kept.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
sequba pushed a commit that referenced this pull request Jul 23, 2026
## What & why

Implements **SORT** (`HF-69`, child of HF-28 "Modern dynamic array
functions", sibling of the shipped SEQUENCE and of VSTACK/HSTACK). Adds
`SORT(array, [sort_index], [sort_order], [by_col])` as a dynamic array
function.

Tests: handsontable/hyperformula-tests#24 (paired).
Sibling PR: #1708 (UNIQUE / HF-68).
ADR: `docs/adr/2026-07-13-sort-unique-array-functions.md`.

## Behavior

- Returns an array the **same shape** as the input.
- `sort_index` (default 1): 1-based index into the sort dimension.
- `sort_order`: `1` ascending (default) or `-1` descending.
- `by_col`: `FALSE` (default) reorders rows; `TRUE` reorders columns.
- Ordering reuses `ArithmeticHelper` (mixed types: numbers < text <
logical; empties; locale collation via
`caseSensitive`/`accentSensitive`) and is **stable** — ties keep input
order.

## Design

Mirrors the SEQUENCE/FILTER machinery: `sizeOfResultArrayMethod` +
`vectorizationForbidden: true`, runtime via `runFunction` returning
`SimpleRangeValue`/`CellError`, parse-time size method returning a
**fresh** `ArraySize` (the input's `isRef` flag is dropped — a
ref-flagged size is treated as scalar and would collapse the spill).

## Notes — divergences from Excel (surfaced here + inline + in tests)

- **`sort_order` is strictly `{1, -1}`**; any other value → `#VALUE!`.
Excel documents only `{1,-1}`; the reported "`sort_order=0` does not
error" quirk is undocumented and **could not be re-verified against live
Excel in this environment**, so the strict documented contract was
chosen (see ADR `dec_2`, `con_1`). Flagged for live-Excel/Kuba
confirmation.
- **Multi-key array-constant `sort_index`** (e.g. `{1,2}`) is **not
supported in v1** (documented in `known-limitations.md`; ADR `dec_6`).
- In-range errors propagate (first error found; ADR `dec_7`).

## Error-type map

`sort_order ∉ {1,-1}` → `#VALUE!` (BadMode) · `sort_index < 1` →
`#VALUE!` (LessThanOne) · `sort_index >` dimension → `#VALUE!`
(ValueLarge) · in-range error → propagate · wrong arity → `#N/A`.

## Definition of Done

- [x] Production code (`SortPlugin.ts`, registered via
`plugin/index.ts`)
- [x] i18n — all 17 language packs (authoritative MS Functions
Translator names; enUS inherits enGB)
- [x] Tests (paired tests PR) — across the standard array-function
groups, dual-env safe
- [x] Docs — `built-in-functions.md`, `known-limitations.md`
- [x] JSDoc on all methods
- [x] CHANGELOG entry
- [x] ADR with audit-verified citations

Source: https://app.clickup.com/t/86c89q1tt

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Self-contained new array function following existing SEQUENCE/FILTER
patterns; no changes to auth, persistence, or core recalculation beyond
registering one plugin.
> 
> **Overview**
> Adds the **SORT** dynamic array function: `SORT(Array, [SortIndex],
[SortOrder], [ByCol])` returns the input range reordered by row
(default) or column, same dimensions as the source.
> 
> Implementation lives in new `SortPlugin.ts`, wired like other array
functions (`sizeOfResultArrayMethod`, `vectorizationForbidden`, spill
size copied from input without propagating `isRef`). Sort keys use
`ArithmeticHelper` (with empty cells forced last); invalid `sort_order`
(not `1` or `-1`), bad `sort_index`, in-range errors, and empty ranges
get the documented `#VALUE!` / `#N/A` / error propagation behavior.
> 
> Docs and changelog are updated; **known-limitations** documents
single-key only, strict sort order, and HF comparison rules. **SORT** is
added to all 17 language packs.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f081be5. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@sequba
sequba merged commit 23a7437 into develop Jul 23, 2026
32 of 34 checks passed
@sequba
sequba deleted the feature/HF-68-unique branch July 23, 2026 14:02

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit a4097a4. Configure here.

}

const result = byCol ? UniquePlugin.transpose(kept) : kept
return SimpleRangeValue.onlyValues(result)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing empty-range crash guard

Medium Severity

UNIQUE can still produce a zero-width result when the input has height but no width (for example after addRows on an empty sheet, then a whole-row reference). That path builds [[]] and later hits ArrayValue, which rejects non-positive dimensions and throws. Sibling SORT already guards this case before building a range value.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit a4097a4. Configure here.

@codecov

codecov Bot commented Jul 23, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.86%. Comparing base (fbb4710) to head (a4097a4).
⚠️ Report is 1 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop    #1708      +/-   ##
===========================================
- Coverage    97.20%   96.86%   -0.35%     
===========================================
  Files          177      178       +1     
  Lines        15546    15611      +65     
  Branches      3444     3460      +16     
===========================================
+ Hits         15112    15122      +10     
- Misses         434      489      +55     
Files with missing lines Coverage Δ
src/i18n/languages/csCZ.ts 100.00% <ø> (ø)
src/i18n/languages/daDK.ts 100.00% <ø> (ø)
src/i18n/languages/deDE.ts 100.00% <ø> (ø)
src/i18n/languages/enGB.ts 100.00% <ø> (ø)
src/i18n/languages/esES.ts 100.00% <ø> (ø)
src/i18n/languages/fiFI.ts 100.00% <ø> (ø)
src/i18n/languages/frFR.ts 100.00% <ø> (ø)
src/i18n/languages/huHU.ts 100.00% <ø> (ø)
src/i18n/languages/idID.ts 100.00% <ø> (ø)
src/i18n/languages/itIT.ts 100.00% <ø> (ø)
... and 9 more

... and 2 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants