Skip to content

Feature/averageifs function - #1732

Merged
sequba merged 14 commits into
developfrom
feature/averageifs-function
Nov 12, 2026
Merged

sequba merged 14 commits into
developfrom
feature/averageifs-function

Conversation

@Tobiadefami

@Tobiadefami Tobiadefami commented Aug 13, 2026 •

Copy link
Copy Markdown
Collaborator

Context

HyperFormula supports AVERAGEIF and other conditional aggregation functions, but it does not support AVERAGEIFS.

This change adds AVERAGEIFS, allowing values to be averaged when all corresponding criteria are satisfied. It uses the existing conditional aggregation and caching infrastructure and includes function metadata, translations, documentation, and tests.

How did you test your changes?

Added tests covering:

  • Required and repeated arguments.
  • Invalid criteria and mismatched range dimensions.
  • Single and multiple criteria.
  • Scalar, reference, range, and calculated-range arguments.
  • Error propagation.
  • Ignoring non-numeric values in the average range.
  • Division-by-zero errors when no numeric values qualify.
  • Valid averages equal to zero.
  • Conditional aggregation caching.
  • Recalculation after changes to the average or criteria ranges, including an average range that is also a criteria range.
  • Three criteria/range pairs, inline-array criteria, and ranges on different sheets.
  • Percent, currency, and date values.

All 33 focused tests passed.

Additionally, I ran:

  • npm run bundle:cjs
  • npm run docs:generate-function-docs

Both commands completed successfully.

Types of changes

  • Breaking change (a fix or a feature because of which an existing functionality doesn't work as
    expected anymore)
  • New feature or improvement (a non-breaking change that adds functionality)
  • Bug fix (a non-breaking change that fixes an issue)
  • Additional language file, or a change to an existing language file (translations)
  • Change to the documentation

Related issues:

Tests: handsontable/hyperformula-tests#36

Checklist:


Note

Medium Risk
Touches core conditional-aggregation evaluation and error handling; behavior must match Excel for edge cases, though it reuses the same pattern as SUMIFS/MAXIFS.

Overview
Adds AVERAGEIFS, which averages values in average_range only where every criteria range/criterion pair is satisfied, aligned with Excel-style multi-criteria behavior like existing SUMIFS / COUNTIFS.

Implementation lives in ConditionalAggregationPlugin: new averageifs handler with repeatLastArgs: 2, wired through computeConditionalAggregationFunction using shared helpers (composeAverageResults, mapToAverageResult, finalizeAverageResult). AVERAGEIF now uses finalizeAverageResult for consistent #DIV/0! and error propagation.

The function is registered in statistical function metadata, listed in CHANGELOG.md, added to proprietary license capability (UNGROUPED_FUNCTIONS), and localized across all language packs.

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

@cla-external-contractor-signup

Copy link
Copy Markdown

@Tobiadefami thanks for the pull request. No CLA step needed here — our records show you signed the Contributor License Agreement on 2026-07-31. That signature came from our previous signing form and has been carried over, so there is nothing for you to re-sign.

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Aug 13, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Preview URL Updated (UTC)
✅ Deployment successful!
View logs
hyperformula-docs 4b0c53f Commit Preview URL

Branch Preview URL
Nov 12 2026, 10:36 AM

@Tobiadefami
Tobiadefami requested a review from sequba August 13, 2026 09:08
@github-actions

github-actions Bot commented Aug 13, 2026 •

Copy link
Copy Markdown

Performance comparison of head (4b0c53f) vs base (ec10dbf)

                                     testName |    base |    head |  change
---------------------------------------------------------------------------
                                      Sheet A |  314.62 |  309.43 |  -1.65%
                                      Sheet B |   110.3 |  104.92 |  -4.88%
                                      Sheet T |   89.39 |   87.35 |  -2.28%
                                Column ranges |  327.66 |   314.2 |  -4.11%
                                Sorted lookup | 10242.6 | 10015.4 |  -2.22%
Sheet A:  change value, add/remove row/column |   13.94 |    11.2 | -19.66%
 Sheet B: change value, add/remove row/column |  109.33 |   89.27 | -18.35%
                   Column ranges - add column |  125.53 |  107.64 | -14.25%
                Column ranges - without batch |  346.17 |  279.98 | -19.12%
                        Column ranges - batch |   81.21 |   68.35 | -15.84%

@marcin-kordas-hoc

Copy link
Copy Markdown
Collaborator

Hey @Tobiadefami — one process thing unrelated to the code itself (which looks solid, see the review above): the paired hyperformula-tests PR seems to have slipped through for this one. The branch feature/averageifs-function is there with real, good tests (function-averageifs.spec.ts + the metadata/i18n/custom-functions updates — I read through them, nice coverage on error propagation, caching, and CRUD recalculation), but there's no PR wrapping it, unlike TAKE (#28) and CHOOSECOLS (#34) which both have theirs open.

Could you open a PR there for this branch? Same thing seems to have happened for #1733's companion branch (fix/averageif-zero-average) — also has commits, also no PR yet. Both should be quick since the work itself is already done and pushed, just need the PR opened so they're visible for review the same way your other two are.

Nothing else blocking here — just flagging it now so it's not a surprise closer to merge.

@Tobiadefami

Copy link
Copy Markdown
Collaborator Author

@marcin-kordas-hoc Done — AVERAGEIFS is in test repo PR 36, and the zero-average fix is in test repo PR 35.

@marcin-kordas-hoc marcin-kordas-hoc left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approving. The engine code here got a clean verdict on 16 Aug and the head has not moved since, so this is about closing the loop on the two things that were still open.

Paired tests now verified against this head. CI on this PR last ran on 13 Aug, while the feature/averageifs-function test branch received commits through 22 Aug — so the green badge above never executed the current test suite. I checked it directly instead: engine 8f54b3ab0 against tests d0f8a4f, function-averageifs.spec.ts → 29/29 passing. The 22 Aug delta (percents, currencies, dates) is structurally the same as the MAXIFS siblings and passes here.

One caveat on the record: I could not re-trigger the workflow — this token has no actions: write, and test.yml has no workflow_dispatch, so the only paths are the re-run button or a new push. Worth one click before merge so the PR's own badge reflects a run that included those tests. My local run is evidence the tests pass, not a substitute for the official record.

Also unable to resolve my own thread on ConditionalAggregationPlugin.ts from here (same token limitation) — your reply on it is correct and it needs no further action, so please mark it resolved.

Merging still waits for the freeze to lift.

sequba commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

AVERAGEIFS drops booleans in average_range; Excel counts them as 1 and 0

Flagging this before merge, since the PR ticks "My change is compatible with Microsoft Excel" and there is a test that currently locks the divergence in.

Repro (verified against this branch at f4ebe7e):

A B
1 =TRUE() y
2 =FALSE() y
3 10 y

=AVERAGEIFS(A1:A3, B1:B3, "y") → 10. Excel returns 3.667, i.e. (1 + 0 + 10) / 3.

Why Excel returns that. The AVERAGEIFS page linked from HF-140 states:

Cells in average_range that contain TRUE evaluate as 1; cells in average_range that contain FALSE evaluate as 0 (zero).

This is one of the spots where Excel deliberately makes AVERAGEIFS differ from AVERAGEIF — the AVERAGEIF page says the opposite:

Cells in range that contain TRUE or FALSE are ignored.

So boolean handling is not something averageifs can inherit from averageif: the two genuinely need different mapping functions. The implementation here reuses AVERAGEIF's shape, so booleans fall through to AverageResult.empty at src/interpreter/plugin/ConditionalAggregationPlugin.ts:253-255.

Suggested fix. In the map function at lines 248-256, handle booleans explicitly before the AverageResult.empty fallback: true → AverageResult.single(1), false → AverageResult.single(0). Text and blank cells should keep being ignored — that matches Excel too.

Test that needs updating alongside it. In the paired tests PR, unit/interpreter/function-averageifs.spec.ts:187 (ignores non-numeric values in the average range) puts =TRUE() in the averaged range and asserts 20. Under Excel semantics that fixture — 10, text, TRUE, empty, 30, all matching the criterion — averages to 41 / 3 ≈ 13.67: text and the empty cell stay ignored, the TRUE counts as 1.

Our preference is to match Excel here, rather than record the current behaviour in docs/guide/list-of-differences.md. AVERAGEIFS is brand-new public surface with no backward-compatibility constraint, the spec is unambiguous, and the alternative means shipping a documented deviation on a function whose whole purpose is Excel parity.


Generated by Claude Code

sequba commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

averageifs duplicates averageif's body — the shared scaffolding should be extracted

averageifs (src/interpreter/plugin/ConditionalAggregationPlugin.ts:228) is structurally a copy of averageif (line 192). Once you set aside how the condition arguments are assembled and the CellError handling, the two are the same code — the reduction tail in particular is character-for-character identical:

// averageif, lines 209-213   ==   averageifs, lines 259-263
if (averageResult instanceof CellError) {
  return averageResult
} else {
  return averageResult.averageValue() ?? new CellError(ErrorType.DIV_BY_ZERO)
}

This isn't a hypothetical maintenance argument — the duplication has already cost a PR. Those two blocks used to disagree: averageif had || where it needed ??, so a legitimate average of 0 came back as #DIV/0!, while the newer averageifs copy was written with ?? from the start. Fixing that needed its own PR (#1733). The divergence is no longer visible here — f4ebe7e merged develop, so both copies now read ?? and I've verified both return 0 for a zero average — but the reason it could happen at all is that the same four lines exist twice.

To be clear about the scope of what I'm suggesting: not one function serving both. The mapping lambda should stay per-function — as I noted in the boolean-handling comment above, Excel deliberately treats TRUE/FALSE differently in AVERAGEIF and AVERAGEIFS, so those two lambdas have to diverge. What's worth extracting is the scaffolding around them:

private computeAverage(
  values: SimpleRangeValue,
  conditionArgs: RawInterpreterValue[],
  functionName: string,
  mapFn: (arg: InternalScalarValue) => AverageResult | CellError,
): InterpreterValue

Both public methods then reduce to assembling their own arguments and passing their own mapFn. One definition of what happens when nothing qualifies, one definition of the CellError short-circuit — so the next fix to either lands in both.

DEV_DOCS asks for exactly this:

Avoid duplication. Extract shared logic instead of copying it, and reuse the existing helpers and abstractions of the codebase.

And this file already demonstrates the pattern: mapToRawScalarValue (line 65) is shared by four call sites across SUMIF/SUMIFS/MINIFS/MAXIFS, and zeroForInfinite (line 57) by two, rather than being inlined into each function.


Generated by Claude Code

@sequba sequba left a comment

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.

One inline note on the Portuguese translation, with a broader ask: the localized names added here should each be confirmed against the sources DEV_DOCS lists, rather than inferred from the neighbouring entries in the same pack — ptPT.ts turns out not to be internally consistent, so its neighbours aren't a safe reference.


Generated by Claude Code

Comment thread hyperformula/src/i18n/languages/ptPT.ts Resolved

@sequba sequba left a comment

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.

Three code-quality notes on the new averageifs method, grouped into one review since they all sit within lines 220-256 and none of them blocks the PR:

  1. Line 220 — the JSDoc names the arguments AverageRange/CriterionRange1/Criterion1, while this same PR publishes average_range/criteria_range1/criteria1 through getFunctionDetails and the generated docs page.
  2. Line 241 — composeFunction is hoisted out of computeFn but the map lambda isn't, so the latter is rebuilt per output cell under vectorization. Neither captures anything; both belong at module level.
  3. Line 248 — the lambda re-implements the CellError/ExtendedNumber dispatch that mapToRawScalarValue (line 65) already provides for the four *IF(S) siblings. Note the sequencing caveat there: if the boolean-handling fix lands, extending the helper is probably better than reusing it as-is.

These are separate from, and smaller than, the two points I raised as top-level comments (Excel boolean semantics, and the averageif/averageifs duplication).


Generated by Claude Code

@Tobiadefami

Copy link
Copy Markdown
Collaborator Author

AVERAGEIFS drops booleans in average_range; Excel counts them as 1 and 0

Flagging this before merge, since the PR ticks "My change is compatible with Microsoft Excel" and there is a test that currently locks the divergence in.

Repro (verified against this branch at f4ebe7e):

A B
1 =TRUE() y
2 =FALSE() y
3 10 y
=AVERAGEIFS(A1:A3, B1:B3, "y") → 10. Excel returns 3.667, i.e. (1 + 0 + 10) / 3.

Why Excel returns that. The AVERAGEIFS page linked from HF-140 states:

Cells in average_range that contain TRUE evaluate as 1; cells in average_range that contain FALSE evaluate as 0 (zero).

This is one of the spots where Excel deliberately makes AVERAGEIFS differ from AVERAGEIF — the AVERAGEIF page says the opposite:

Cells in range that contain TRUE or FALSE are ignored.

So boolean handling is not something averageifs can inherit from averageif: the two genuinely need different mapping functions. The implementation here reuses AVERAGEIF's shape, so booleans fall through to AverageResult.empty at src/interpreter/plugin/ConditionalAggregationPlugin.ts:253-255.

Suggested fix. In the map function at lines 248-256, handle booleans explicitly before the AverageResult.empty fallback: true → AverageResult.single(1), false → AverageResult.single(0). Text and blank cells should keep being ignored — that matches Excel too.

Test that needs updating alongside it. In the paired tests PR, unit/interpreter/function-averageifs.spec.ts:187 (ignores non-numeric values in the average range) puts =TRUE() in the averaged range and asserts 20. Under Excel semantics that fixture — 10, text, TRUE, empty, 30, all matching the criterion — averages to 41 / 3 ≈ 13.67: text and the empty cell stay ignored, the TRUE counts as 1.

Our preference is to match Excel here, rather than record the current behaviour in docs/guide/list-of-differences.md. AVERAGEIFS is brand-new public surface with no backward-compatibility constraint, the spec is unambiguous, and the alternative means shipping a documented deviation on a function whose whole purpose is Excel parity.

Generated by Claude Code

Thanks for flagging. I verified this directly in Excel for the web. With TRUE, FALSE, and 10 in average_range, and all three rows matching the criterion, AVERAGEIFS returns 10. This shows that Boolean values in average_range are ignored rather than coerced to 1 and 0. The cited Microsoft documentation refers more generally to cells in “range” and is ambiguous about whether that means average_range.

I have attached the reproduction screenshot for reference.
Screenshot_20260904_203158

Tobiadefami and others added 3 commits September 4, 2026 20:59
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@cursor

cursor Bot commented Oct 21, 2026

Copy link
Copy Markdown

Bugbot is paused — on-demand spend limit reached

Bugbot uses usage-based billing for this team and has hit its on-demand spend limit.

A team admin can raise the spend limit in the Cursor dashboard, or wait for the next billing cycle to continue.

@marcin-kordas-hoc marcin-kordas-hoc left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

question: the 2 September PR comment asking for shared scaffolding between averageif and averageifs has no reply. Is the shared finalizeAverageResult meant as the answer? A one-line reply on that comment would close it.

nit: the description lists tests for "Public function metadata" and "The Portuguese translation" and says 28 focused tests passed. Both tests were removed from hyperformula-tests#36 on request, and function-averageifs.spec.ts now has 33 tests.

@Tobiadefami

Copy link
Copy Markdown
Collaborator Author

@marcin-kordas-hoc Yes. The shared scaffolding asked for in this comment is finalizeAverageResult, added in c6e1fb5. The CellError short-circuit and the #DIV/0! fallback for "nothing qualifies" now live in that one helper, and both averageif and averageifs call it. Each function keeps its own mapping and combining functions, as the comment suggested.

@Tobiadefami
Tobiadefami requested review from marcin-kordas-hoc and removed request for marcin-kordas-hoc November 9, 2026 09:26

@marcin-kordas-hoc marcin-kordas-hoc left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approving again at bac0f10. Since my approval at 545f0d4, this branch and hyperformula-tests#36 have only merged develop. The changed lines of both pull requests are the same; only the context around the CHANGELOG entry moved. Both points of that review are closed. Your reply names finalizeAverageResult, which both averageif and averageifs now return through, and the description says 33 tests without listing the two removed ones. With Jest at bac0f10 and ab1b684, function-averageifs.spec.ts, function-averageif.spec.ts and custom-functions.spec.ts pass (89 tests), and CI passed with the paired branch checked out after its last push.

@sequba
sequba merged commit 6c5fe0f into develop Nov 12, 2026
30 of 32 checks passed
@sequba
sequba deleted the feature/averageifs-function branch November 12, 2026 10:35
@codecov

codecov Bot commented Nov 12, 2026

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff            @@
##           develop    #1732   +/-   ##
========================================
  Coverage    97.37%   97.37%           
========================================
  Files          209      209           
  Lines        16557    16580   +23     
  Branches      3683     3689    +6     
========================================
+ Hits         16122    16145   +23     
- Misses         427      435    +8     
+ Partials         8        0    -8     
Files with missing lines Coverage Δ
hyperformula/src/i18n/languages/csCZ.ts 100.00% <ø> (ø)
hyperformula/src/i18n/languages/daDK.ts 100.00% <ø> (ø)
hyperformula/src/i18n/languages/deDE.ts 100.00% <ø> (ø)
hyperformula/src/i18n/languages/enGB.ts 100.00% <ø> (ø)
hyperformula/src/i18n/languages/esES.ts 100.00% <ø> (ø)
hyperformula/src/i18n/languages/fiFI.ts 100.00% <ø> (ø)
hyperformula/src/i18n/languages/frFR.ts 100.00% <ø> (ø)
hyperformula/src/i18n/languages/huHU.ts 100.00% <ø> (ø)
hyperformula/src/i18n/languages/idID.ts 100.00% <ø> (ø)
hyperformula/src/i18n/languages/itIT.ts 100.00% <ø> (ø)
... and 10 more

... and 5 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