Skip to content

feat: implement SORT dynamic array function (HF-69) - #1707

Merged
sequba merged 10 commits into
developfrom
feature/HF-69-sort
Jul 23, 2026
Merged

sequba merged 10 commits into
developfrom
feature/HF-69-sort

Conversation

@marcin-kordas-hoc

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

Copy link
Copy Markdown
Collaborator

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

  • Production code (SortPlugin.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/86c89q1tt


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.

Reviewed by Cursor Bugbot for commit f081be5. 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 f081be5
🔍 Latest deploy log https://app.netlify.com/projects/hyperformula-dev-docs/deploys/6a61ed3152449c00089ca778
😎 Deploy Preview https://deploy-preview-1707--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

Comment thread src/interpreter/plugin/SortPlugin.ts Resolved
@github-actions

github-actions Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Performance comparison of head (f081be5) vs base (6e87a37)

                                     testName |    base |    head | change
--------------------------------------------------------------------------
                                      Sheet A |     479 |  483.41 | +0.92%
                                      Sheet B |   149.8 |  152.86 | +2.04%
                                      Sheet T |  134.23 |  136.48 | +1.68%
                                Column ranges |  461.23 |  460.29 | -0.20%
                                Sorted lookup | 14245.2 | 14031.9 | -1.50%
Sheet A:  change value, add/remove row/column |   13.98 |   14.44 | +3.29%
 Sheet B: change value, add/remove row/column |  126.77 |  124.21 | -2.02%
                   Column ranges - add column |  149.39 |   141.8 | -5.08%
                Column ranges - without batch |  435.32 |  433.46 | -0.43%
                        Column ranges - batch |  109.83 |  109.66 | -0.15%

@marcin-kordas-hoc
marcin-kordas-hoc requested a review from sequba July 16, 2026 11:58
Add SORT(array, [sort_index], [sort_order], [by_col]) as a dynamic array
function, mirroring the SEQUENCE/FILTER machinery. Ordering reuses
ArithmeticHelper (mixed types, empties, collation) and is stable, so ties
keep input order. sort_order is validated strictly to {1,-1}; sort_index is
bounds-checked; errors in the input range propagate. Output shape equals the
input shape.

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/86c89q1tt
ADR: docs/adr/2026-07-13-sort-unique-array-functions.md

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Comment thread src/interpreter/plugin/SortPlugin.ts Resolved
marcin-kordas-hoc and others added 2 commits July 21, 2026 10:20
…HF-69)

A whole-column reference to an empty sheet resolves to a zero-row range.
The row/column sort paths then handed an empty 2-D array to
SimpleRangeValue.onlyValues, which reads data[0].length and threw an
uncaught TypeError. Guard the empty case up front and return #N/A
(Empty range not allowed), matching UNIQUE and FILTER.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Without enableArrayArithmeticForArguments, an array expression passed as
the first argument (e.g. =SORT(A1:A3*2)) is coerced as a scalar and only
the first cell is computed. Matches FILTER/VSTACK/HSTACK so computed
arrays can be sorted without an ARRAYFORMULA wrapper.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

@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 010aa8a. Configure here.

Comment thread src/interpreter/plugin/SortPlugin.ts Resolved
marcin-kordas-hoc and others added 4 commits July 21, 2026 21:21
Excel's SORT places blank cells at the end of the result in both ascending
and descending order, rather than coercing them to 0 and ordering by value.
Force empties last (direction-independent) in the comparator before
delegating to ArithmeticHelper.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
HF converts overflow/NaN to #NUM! during argument evaluation, so a
non-finite sort_index never reaches the function body — the guard was dead
code. Out-of-range indices are still handled by the <1 / >dimension checks.
Removes the last uncovered lines in SortPlugin.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Do you think we should keep ADRs in repo? If so, I'd rather not have them in docs dir.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Personally, I think we can keep some files describing the general architectural decisions, but ADR about a specific function implementation won't be useful in implementing future features so it should be removed. If there are any non-obvious decisions or implementation details, they should be noted in the code comments.

@sequba sequba Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Ok, let's keep it but move it to the hyperformula-tests repo please (dev_docs directory)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done ✅ Moved it to hyperformula-tests under dev_docs/2026-07-13-sort-unique-array-functions.md and dropped it from the engine repo here. Applied to both PRs — paired tests PRs: SORT handsontable/hyperformula-tests#24, UNIQUE handsontable/hyperformula-tests#25 (paired with #1708).

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 added a commit that referenced this pull request Jul 23, 2026
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 and others added 2 commits July 23, 2026 12:29
Describe the sort_order contract on its own terms instead of naming Excel
in a published surface (JSDoc feeds the API docs). Internal implementation
comments that reference Excel as the behavioural oracle are kept.

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

codecov Bot commented Jul 23, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.41270% with 1 line in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (develop@6e87a37). Learn more about missing BASE report.

Files with missing lines Patch % Lines
src/interpreter/plugin/SortPlugin.ts 98.38% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             develop    #1707   +/-   ##
==========================================
  Coverage           ?   97.18%           
==========================================
  Files              ?      177           
  Lines              ?    15546           
  Branches           ?     3444           
==========================================
  Hits               ?    15109           
  Misses             ?      437           
  Partials           ?        0           
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
🚀 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.

@sequba
sequba merged commit fbb4710 into develop Jul 23, 2026
33 checks passed
@sequba
sequba deleted the feature/HF-69-sort branch July 23, 2026 13:59
sequba added a commit that referenced this pull request Jul 23, 2026
## 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

- [x] Production code (`UniquePlugin.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/86c89q1tq

<!-- CURSOR_SUMMARY -->
---

> [!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.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
a4097a4. 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>
Co-authored-by: Kuba Sekowski <jakub.sekowski@handsontable.com>
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