Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

perf(engine-formula): reuse repeated criteria and cache range indexes (#8176)

wpxp123456494981242e85
diff --git a/packages/engine-formula/src/engine/utils/__tests__/value-object.spec.ts b/packages/engine-formula/src/engine/utils/__tests__/value-object.spec.ts
index c8fa5bd809..96ee56cd1c 100644
--- a/packages/engine-formula/src/engine/utils/__tests__/value-object.spec.ts
+++ b/packages/engine-formula/src/engine/utils/__tests__/value-object.spec.ts
@@ -441,4 +441,177 @@ describe('Conditional aggregate indexed equality semantics', () => {
range.set(0, 0, StringValueObject.create('Beta'));
expect(getPairedRangeAndCriteriaResult([range, criteria], params).map((row) => row[0].getValue())).toEqual([0, 2]);
});
+
+ it.each(['COUNTIFS', 'SUMIFS', 'AVERAGEIFS', 'MINIFS', 'MAXIFS'])(
+ '%s aggregates indexed positions like a single criterion evaluation',
+ (formulaName) => {
+ const keys = ArrayValueObject.createByArray([['a'], ['b'], ['a'], ['c'], ['b'], ['a']]);
+ const amounts = ArrayValueObject.createByArray([[1], [2], [3], [4], [5], [6]]);
+ const criteria = ArrayValueObject.createByArray([['a'], ['b'], ['x'], [null]]);
+ const params = {
+ formulaName,
+ maxRowLength: 4,
+ maxColumnLength: 1,
+ isNumberSensitive: true,
+ targetRange: amounts,
+ };
+ const result = getPairedRangeAndCriteriaResult([keys, criteria], params);
+ const expected = [StringValueObject.create('a'), StringValueObject.create('b'), StringValueObject.create('x'), NullValueObject.create()]
+ .map((criterion) => getPairedRangeAndCriteriaResult([keys, criterion], { ...params, maxRowLength: 1, maxColumnLength: 1 })[0][0].getValue());
+ expect(result.map((row) => row[0].getValue())).toEqual(expected);
+ }
+ );
+
+ it('keeps repeated criteria keys distinct when text contains the key separator', () => {
+ // Excel stores U+0000 in OOXML as `_x0000_`, so imported cells can contain it.
+ // These two criteria tuples must not share a cache key.
+ const nul = String.fromCharCode(0);
+ const firstKey = `A${nul}s:date1900:B`;
+ const secondKey = `B${nul}s:date1900:C`;
+ const keys = ArrayValueObject.createByArray([[firstKey], ['A']]);
+ const groups = ArrayValueObject.createByArray([['C'], [secondKey]]);
+ const amounts = ArrayValueObject.createByArray([[31], [37]]);
+
+ const result = getPairedRangeAndCriteriaResult([
+ keys,
+ ArrayValueObject.createByArray([[firstKey], ['A']]),
+ groups,
+ ArrayValueObject.createByArray([['C'], [secondKey]]),
+ ], {
+ formulaName: 'SUMIFS',
+ maxRowLength: 2,
+ maxColumnLength: 1,
+ isNumberSensitive: true,
+ targetRange: amounts,
+ });
+
+ expect(result.map((row) => row[0].getValue())).toEqual([31, 37]);
+ });
+
+ it('keeps date-formatted serials distinct from plain numbers in cached criteria', () => {
+ // Date comparisons round the serial, so `1` formatted as a date matches a
+ // date-formatted 1.000000001 while a plain `1` does not.
+ const range = ArrayValueObject.create({
+ calculateValueList: [[NumberValueObject.create(1.000000001, 'yyyy-mm-dd')]],
+ rowCount: 1,
+ columnCount: 1,
+ unitId: '',
+ sheetId: '',
+ row: -1,
+ column: -1,
+ });
+ const amounts = ArrayValueObject.create({
+ calculateValueList: [[NumberValueObject.create(7)]],
+ rowCount: 1,
+ columnCount: 1,
+ unitId: '',
+ sheetId: '',
+ row: -1,
+ column: -1,
+ });
+ const criteria = ArrayValueObject.create({
+ calculateValueList: [[NumberValueObject.create(1, 'yyyy-mm-dd')], [NumberValueObject.create(1)]],
+ rowCount: 2,
+ columnCount: 1,
+ unitId: '',
+ sheetId: '',
+ row: -1,
+ column: -1,
+ });
+
+ const result = getPairedRangeAndCriteriaResult([range, criteria], {
+ formulaName: 'SUMIFS',
+ maxRowLength: 2,
+ maxColumnLength: 1,
+ isNumberSensitive: true,
+ targetRange: amounts,
+ });
+
+ expect(result.map((row) => row[0].getValue())).toEqual([7, 0]);
+ });
+
+ it('keeps date-formatted serials that round to different dates distinct', () => {
+ // Date comparison rounds the serial at 1e-8, so these two values land on
+ // different dates even though they scale to the same 12-digit number.
+ const lower = 45000.00000000499;
+ const upper = 45000.000000005006;
+ const range = ArrayValueObject.create({
+ calculateValueList: [[NumberValueObject.create(lower, 'yyyy-mm-dd')]],
+ rowCount: 1,
+ columnCount: 1,
+ unitId: '',
+ sheetId: '',
+ row: -1,
+ column: -1,
+ });
+ const amounts = ArrayValueObject.create({
+ calculateValueList: [[NumberValueObject.create(7)]],
+ rowCount: 1,
+ columnCount: 1,
+ unitId: '',
+ sheetId: '',
+ row: -1,
+ column: -1,
+ });
+ const criteria = ArrayValueObject.create({
+ calculateValueList: [
+ [NumberValueObject.create(lower, 'yyyy-mm-dd')],
+ [NumberValueObject.create(upper, 'yyyy-mm-dd')],
+ ],
+ rowCount: 2,
+ columnCount: 1,
+ unitId: '',
+ sheetId: '',
+ row: -1,
+ column: -1,
+ });
+
+ const result = getPairedRangeAndCriteriaResult([range, criteria], {
+ formulaName: 'SUMIFS',
+ maxRowLength: 2,
+ maxColumnLength: 1,
+ isNumberSensitive: true,
+ targetRange: amounts,
+ });
+
+ expect(result.map((row) => row[0].getValue())).toEqual([7, 0]);
+ });
+
+ it('evaluates the repeated blank cells of a whole-column criteria range once', () => {
+ const size = 200;
+ const keyCount = 20;
+ const range = ArrayValueObject.createByArray(Array.from({ length: size }, (_, i) => [`k${i % keyCount}`]));
+ const amounts = ArrayValueObject.createByArray(Array.from({ length: size }, (_, i) => [i + 1]));
+ const criteria = ArrayValueObject.createByArray([
+ ...Array.from({ length: keyCount }, (_, i) => [`k${i}`]),
+ ...Array.from({ length: 80 }, () => [null]),
+ ]);
+ const params = {
+ formulaName: 'SUMIFS',
+ maxRowLength: 100,
+ maxColumnLength: 1,
+ isNumberSensitive: true,
+ targetRange: amounts,
+ };
+
+ const reads = vi.spyOn(range, 'get');
+ try {
+ const result = getPairedRangeAndCriteriaResult([range, criteria], params);
+ const expected = Array.from({ length: 100 }, (_, i) => {
+ if (i >= keyCount) {
+ return 0;
+ }
+ let total = 0;
+ for (let row = i; row < size; row += keyCount) {
+ total += row + 1;
+ }
+ return total;
+ });
+ expect(result.map((row) => row[0].getValue())).toEqual(expected);
+ // Blank criteria repeat, so they must reuse one evaluation instead of rescanning per cell.
+ expect(reads.mock.calls.length).toBeLessThan(size * 10);
+ } finally {
+ reads.mockRestore();
+ }
+ });
});
diff --git a/packages/engine-formula/src/engine/utils/value-object.ts b/packages/engine-formula/src/engine/utils/value-object.ts
index 347223655b..ec76db420c 100644
--- a/packages/engine-formula/src/engine/utils/value-object.ts
+++ b/packages/engine-formula/src/engine/utils/value-object.ts
@@ -15,9 +15,10 @@
*/
import type { ICellData, Nullable } from '@univerjs/core';
+import { CellValueType } from '@univerjs/core';
+import type { FormulaCalculationCache } from '../../services/formula-cache.service';
import type { BaseReferenceObject, FunctionVariantType } from '../reference-object/base-reference-object';
import type { BaseValueObject } from '../value-object/base-value-object';
-import { CellValueType } from '@univerjs/core';
import { ERROR_TYPE_SET, ErrorType } from '../../basics/error-type';
import { compareToken } from '../../basics/token';
import { CellReferenceObject } from '../reference-object/cell-reference-object';
@@ -331,8 +332,49 @@ function getEqualityValueKeys(value: BaseValueObject): Array<string | number> {
return keys;
}
-function buildEqualityIndex(range: ArrayValueObject): Map<string | number, Array<[number, number]>> {
- const index = new Map<string | number, Array<[number, number]>>();
+type EqualityIndex = Map<string | number, Array<[number, number]>>;
+
+/**
+ * Equality indexes keyed by the calculation pass they were built for.
+ *
+ * Range arrays are cached per calculation pass and are not mutated while the pass is
+ * running, so one index can serve every formula that reads the same range. Keying the
+ * outer map by the pass cache makes the whole entry disappear together with the pass,
+ * which is also why no change tracking is needed.
+ */
+const passEqualityIndexes = new WeakMap<FormulaCalculationCache, Map<ArrayValueObject, EqualityIndex>>();
+
+function getOrBuildEqualityIndex(
+ range: ArrayValueObject,
+ localIndexes: Map<ArrayValueObject, EqualityIndex>
+): EqualityIndex {
+ const calculationCache = range.getCalculationCache();
+ if (calculationCache == null || calculationCache.closed) {
+ let index = localIndexes.get(range);
+ if (index === undefined) {
+ index = buildEqualityIndex(range);
+ localIndexes.set(range, index);
+ }
+ return index;
+ }
+
+ let indexes = passEqualityIndexes.get(calculationCache);
+ if (indexes === undefined) {
+ indexes = new Map();
+ passEqualityIndexes.set(calculationCache, indexes);
+ }
+
+ let index = indexes.get(range);
+ if (index === undefined) {
+ index = buildEqualityIndex(range);
+ indexes.set(range, index);
+ }
+
+ return index;
+}
+
+function buildEqualityIndex(range: ArrayValueObject): EqualityIndex {
+ const index: EqualityIndex = new Map();
range.iterator((value, row, column) => {
if (!value) {
return;
@@ -351,7 +393,7 @@ function buildEqualityIndex(range: ArrayValueObject): Map<string | number, Array
}
function getIndexedPositions(
- index: Map<string | number, Array<[number, number]>>,
+ index: EqualityIndex,
keys: Array<string | number>,
range: ArrayValueObject
): Array<[number, number]> | undefined {
@@ -400,31 +442,69 @@ function getExactCriteriaKeys(criteria: Nullable<BaseValueObject>): Array<string
return keys.length > 0 ? keys : undefined;
}
-function getCriteriaCacheKey(criteria: Array<Nullable<BaseValueObject>>): string | number | undefined {
- if (criteria.length === 0 || criteria.some((value) => getExactCriteriaKeys(value) === undefined)) {
- return undefined;
- }
- const values = criteria.map((value) => value!.getValue());
- return values.length === 1 ? values[0] as string | number : JSON.stringify(values);
+/**
+ * Upper bound of the repeated-criteria cache. Repeated criteria are few in practice
+ * (blank cells, a handful of keys); the bound guards against a criteria array that is
+ * entirely made of distinct values.
+ */
+const MAX_REPEATED_CRITERIA_RESULTS = 4096;
+
+/**
+ * Build a cache key for one tuple of criteria values.
+ *
+ * Every value kind gets its own tagged key instead of requiring an exact equality
+ * match, so repeated criteria — typically the trailing blank cells of a whole-column
+ * criteria reference — reuse a single evaluation instead of rescanning the range once
+ * per cell.
+ */
+function getCriteriaCacheKey(criteria: Array<Nullable<BaseValueObject>>): string {
+ let key = '';
+ for (const value of criteria) {
+ const segment = getCriteriaKeySegment(value);
+ // Length-prefix every segment: criteria text may contain the separator, and an
+ // ambiguous join would let two different tuples share one cache entry.
+ key += `${segment.length}:${segment}`;
+ }
+ return key;
+}
+
+function getCriteriaKeySegment(value: Nullable<BaseValueObject>): string {
+ if (value == null || value.isNull()) {
+ return 'n';
+ }
+ if (value.isBoolean()) {
+ return `b:${value.getValue()}`;
+ }
+ if (value.isNumber()) {
+ const pattern = value.getPattern();
+ // Keep the exact double. Every comparison is a function of it, but two values
+ // that `stripErrorMargin` folds together can still compare differently: date
+ // comparisons round the serial at 1e-8 before comparing, so 45000.00000000499
+ // and 45000.000000005006 land on different dates.
+ const serial = String(value.getValue());
+ // A date-formatted serial also compares differently from a plain number of the
+ // same value, so the pattern is part of the key.
+ return pattern ? `#:${pattern}:${serial}` : `#:${serial}`;
+ }
+ if (value.isError()) {
+ return `e:${value.getValue()}`;
+ }
+ // Text criteria may be parsed as dates, which depends on the date system.
+ return `s:${value.getDateSystem()}:${value.getValue()}`;
}
function getCriteriaPositions(
pairs: Array<{ range: ArrayValueObject; criteriaArray: ArrayValueObject }>,
- indexes: Map<ArrayValueObject, Map<string | number, Array<[number, number]>>>,
row: number,
- column: number
+ column: number,
+ localIndexes: Map<ArrayValueObject, EqualityIndex>
): Array<[number, number]> | undefined {
for (const { range, criteriaArray } of pairs) {
const keys = getExactCriteriaKeys(criteriaArray.get(row, column));
if (!keys) {
continue;
}
- let index = indexes.get(range);
- if (!index) {
- index = buildEqualityIndex(range);
- indexes.set(range, index);
- }
- const positions = getIndexedPositions(index, keys, range);
+ const positions = getIndexedPositions(getOrBuildEqualityIndex(range, localIndexes), keys, range);
// ponytail: stop at the first selective index; compare all criteria on its candidates.
if (positions !== undefined) {
return positions;
@@ -434,20 +514,13 @@ function getCriteriaPositions(
function getConditionalAggregateResult(
formulaName: string,
- comparison: ArrayValueObject,
- targetRange?: ArrayValueObject
+ matchedCount: number,
+ picked?: ArrayValueObject
): BaseValueObject | undefined {
if (formulaName === 'COUNTIFS') {
- let count = 0;
- comparison.iterator((value) => {
- if (value?.isBoolean() && value.getValue() === true) {
- count++;
- }
- });
- return NumberValueObject.create(count);
+ return NumberValueObject.create(matchedCount);
}
- const picked = targetRange?.pick(comparison);
switch (formulaName) {
case 'SUMIFS':
return picked!.sum();
@@ -507,9 +580,12 @@ export function getPairedRangeAndCriteriaResult(
return criteria.isArray() &&
(criteria as ArrayValueObject).getRowCount() * (criteria as ArrayValueObject).getColumnCount() > 1;
});
- const useEqualityIndex = isNumberSensitive && maxRowLength * maxColumnLength > 1 && arrayPairs.length > 0;
- const repeatedResults = new Map<string | number, BaseValueObject>();
- const equalityIndexes = new Map<ArrayValueObject, Map<string | number, Array<[number, number]>>>();
+ const hasArrayResult = maxRowLength * maxColumnLength > 1;
+ const useEqualityIndex = isNumberSensitive && hasArrayResult && arrayPairs.length > 0;
+ // A single cell result is evaluated once, so caching repeated criteria only pays off for arrays.
+ const useRepeatedCriteria = hasArrayResult && arrayPairs.length > 0;
+ const repeatedResults = new Map<string, BaseValueObject>();
+ const localIndexes = new Map<ArrayValueObject, EqualityIndex>();
/**
* Iterate through all criteria values for each dimension, calculate the comparison result with the corresponding range, and then calculate the Boolean intersection of all comparison results as the final result for that dimension criteria value.
@@ -521,18 +597,18 @@ export function getPairedRangeAndCriteriaResult(
firstPair.criteriaArray.iterator((_, rowIndex, columnIndex) => {
let finalCompareResult: ArrayValueObject | undefined;
let positions: Array<[number, number]> | undefined;
- const cacheKey = useEqualityIndex
+ const cacheKey = useRepeatedCriteria
? getCriteriaCacheKey(arrayPairs.map(({ criteriaArray }) => criteriaArray.get(rowIndex, columnIndex)))
: undefined;
const cached = cacheKey === undefined ? undefined : repeatedResults.get(cacheKey);
- if (cached) {
+ if (cached !== undefined) {
results[rowIndex] ??= [];
results[rowIndex][columnIndex] = cached;
return;
}
if (useEqualityIndex) {
- positions = getCriteriaPositions(arrayPairs, equalityIndexes, rowIndex, columnIndex);
+ positions = getCriteriaPositions(arrayPairs, rowIndex, columnIndex, localIndexes);
if (positions?.length === 0) {
results[rowIndex] ??= [];
results[rowIndex][columnIndex] = formulaName === 'AVERAGEIFS'
@@ -542,6 +618,21 @@ export function getPairedRangeAndCriteriaResult(
}
}
+ /**
+ * Indexed positions already are the match set, so a single pair can be aggregated
+ * without materializing the comparison mask or picking through it.
+ */
+ if (positions !== undefined && rangeAndCriteriaArrays.length === 1) {
+ const picked = targetRange ? pickRangePositions(targetRange, positions) : undefined;
+ const result = getConditionalAggregateResult(formulaName, positions.length, picked);
+ results[rowIndex] ??= [];
+ results[rowIndex][columnIndex] = result as BaseValueObject;
+ if (cacheKey !== undefined && result && repeatedResults.size < MAX_REPEATED_CRITERIA_RESULTS) {
+ repeatedResults.set(cacheKey, result);
+ }
+ return;
+ }
+
rangeAndCriteriaArrays.forEach(({ range: sourceRange, criteriaArray }) => {
// Preserve paired row/column offsets and reuse the existing comparison semantics.
const range = positions === undefined ? sourceRange : pickRangePositions(sourceRange, positions);
@@ -568,14 +659,25 @@ export function getPairedRangeAndCriteriaResult(
});
const aggregateRange = positions === undefined || !targetRange ? targetRange : pickRangePositions(targetRange, positions);
- const result = getConditionalAggregateResult(formulaName, finalCompareResult as ArrayValueObject, aggregateRange);
+ let matchedCount = 0;
+ if (formulaName === 'COUNTIFS') {
+ (finalCompareResult as ArrayValueObject).iterator((value) => {
+ if (value?.isBoolean() && value.getValue() === true) {
+ matchedCount++;
+ }
+ });
+ }
+ const picked = formulaName === 'COUNTIFS' || aggregateRange === undefined
+ ? undefined
+ : aggregateRange.pick(finalCompareResult as ArrayValueObject);
+ const result = getConditionalAggregateResult(formulaName, matchedCount, picked);
if (!results[rowIndex]) {
results[rowIndex] = [];
}
results[rowIndex][columnIndex] = result as BaseValueObject;
- if (cacheKey !== undefined && result) {
+ if (cacheKey !== undefined && result && repeatedResults.size < MAX_REPEATED_CRITERIA_RESULTS) {
repeatedResults.set(cacheKey, result);
}
});
diff --git a/packages/engine-formula/src/engine/value-object/array-value-object.ts b/packages/engine-formula/src/engine/value-object/array-value-object.ts
index ce9d8a157d..4f9a4b00a8 100644
--- a/packages/engine-formula/src/engine/value-object/array-value-object.ts
+++ b/packages/engine-formula/src/engine/value-object/array-value-object.ts
@@ -15,9 +15,9 @@
*/
import type { Nullable } from '@univerjs/core';
+import { DateSystem, isRealNum } from '@univerjs/core';
import type { FormulaCalculationCache } from '../../services/formula-cache.service';
import type { callbackMapFnType, IArrayValueObject } from './base-value-object';
-import { DateSystem, isRealNum } from '@univerjs/core';
import { BooleanValue } from '../../basics/common';
import { ERROR_TYPE_SET, ErrorType } from '../../basics/error-type';
import { regexTestArrayValue } from '../../basics/regex';
@@ -116,6 +116,10 @@ export class ArrayValueObject extends BaseValueObject {
return this;
}
+ getCalculationCache() {
+ return this._calculationCache;
+ }
+
/**
* Create an array value object based on the string or IArrayValueObject data.
* @param rawValue
diff --git a/packages/engine-formula/src/services/__tests__/calculate-formula.service.spec.ts b/packages/engine-formula/src/services/__tests__/calculate-formula.service.spec.ts
index 4b3747fda9..f545432de8 100644
--- a/packages/engine-formula/src/services/__tests__/calculate-formula.service.spec.ts
+++ b/packages/engine-formula/src/services/__tests__/calculate-formula.service.spec.ts
@@ -14,19 +14,22 @@
* limitations under the License.
*/
-import type { ICellData } from '@univerjs/core';
-import { IConfigService, Inject, Injector, ObjectMatrix } from '@univerjs/core';
+import type { ICellData, IWorkbookData } from '@univerjs/core';
+import { CellValueType, IConfigService, Inject, Injector, LocaleType, ObjectMatrix } from '@univerjs/core';
import { describe, expect, it, vi } from 'vitest';
import type { IFormulaDatasetConfig } from '../../basics/common';
import type { IAllRuntimeData } from '../runtime.service';
import { ErrorType } from '../../basics/error-type';
import { ENGINE_FORMULA_PLUGIN_CONFIG_KEY } from '../../config/config';
+import { createCommandTestBed } from '../../engine/analysis/__tests__/create-command-test-bed';
import { Lexer } from '../../engine/analysis/lexer';
import { AstTreeBuilder } from '../../engine/analysis/parser';
import { IFormulaDependencyGenerator } from '../../engine/dependency/formula-dependency';
import { Interpreter } from '../../engine/interpreter/interpreter';
import { createFunctionTestBed } from '../../functions/__tests__/create-function-test-bed';
import { AsyncCustomFunction } from '../../functions/custom-function';
+import { FUNCTION_NAMES_MATH } from '../../functions/math/function-names';
+import { Sumifs } from '../../functions/math/sumifs';
import { CalculateFormulaService, ICalculateFormulaService } from '../calculate-formula.service';
import { IFormulaCurrentConfigService } from '../current-data.service';
import { DependencyManagerService, IDependencyManagerService } from '../dependency-manager.service';
@@ -805,3 +808,102 @@ describe('CalculateFormulaService', () => {
expect(mocks.currentConfigService.loadDataLite).toHaveBeenCalledTimes(5);
});
});
+
+describe('executeFormulas conditional aggregate criteria', () => {
+ it('keeps a date-formatted serial distinct from a plain number', async () => {
+ // Date comparisons round the serial, so a date-formatted `1` matches a
+ // date-formatted 1.000000001 while a plain `1` does not. Both values are
+ // criteria for the same array formula, so they must not share a cache key.
+ const workbook: IWorkbookData = {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ locale: LocaleType.EN_US,
+ name: '',
+ sheetOrder: ['sheet1'],
+ styles: {},
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ name: 'Sheet1',
+ rowCount: 10,
+ columnCount: 10,
+ cellData: {
+ 0: {
+ 0: { v: 1.000000001, t: CellValueType.NUMBER, s: { n: { pattern: 'yyyy-mm-dd' } } },
+ 1: { v: 7, t: CellValueType.NUMBER },
+ 3: { v: 1, t: CellValueType.NUMBER, s: { n: { pattern: 'yyyy-mm-dd' } } },
+ },
+ 1: {
+ 3: { v: 1, t: CellValueType.NUMBER },
+ },
+ },
+ },
+ },
+ };
+
+ const testBed = createCommandTestBed(workbook);
+ testBed.get(IFunctionService).registerExecutors(new Sumifs(FUNCTION_NAMES_MATH.SUMIFS));
+ const service = testBed.get(ICalculateFormulaService);
+
+ const result = await service.executeFormulas({
+ [testBed.unitId]: {
+ [testBed.sheetId]: {
+ 0: { 4: ['=SUMIFS(B1:B1,A1:A1,D1:D2)'] },
+ },
+ },
+ }, testBed.sheetData as never);
+
+ expect(result[testBed.unitId]?.[testBed.sheetId]?.[0]?.[4]).toEqual([
+ { value: [[7], [0]], formula: '=SUMIFS(B1:B1,A1:A1,D1:D2)' },
+ ]);
+ });
+
+ it('keeps date-formatted serials that round to different dates distinct', async () => {
+ // 45000.00000000499 and 45000.000000005006 scale to the same 12-digit number
+ // but date comparison rounds them onto different dates.
+ const lower = 45000.00000000499;
+ const upper = 45000.000000005006;
+ const workbook: IWorkbookData = {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ locale: LocaleType.EN_US,
+ name: '',
+ sheetOrder: ['sheet1'],
+ styles: {},
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ name: 'Sheet1',
+ rowCount: 10,
+ columnCount: 10,
+ cellData: {
+ 0: {
+ 0: { v: lower, t: CellValueType.NUMBER, s: { n: { pattern: 'yyyy-mm-dd' } } },
+ 1: { v: 7, t: CellValueType.NUMBER },
+ 3: { v: lower, t: CellValueType.NUMBER, s: { n: { pattern: 'yyyy-mm-dd' } } },
+ },
+ 1: {
+ 3: { v: upper, t: CellValueType.NUMBER, s: { n: { pattern: 'yyyy-mm-dd' } } },
+ },
+ },
+ },
+ },
+ };
+
+ const testBed = createCommandTestBed(workbook);
+ testBed.get(IFunctionService).registerExecutors(new Sumifs(FUNCTION_NAMES_MATH.SUMIFS));
+ const service = testBed.get(ICalculateFormulaService);
+
+ const result = await service.executeFormulas({
+ [testBed.unitId]: {
+ [testBed.sheetId]: {
+ 0: { 4: ['=SUMIFS(B1:B1,A1:A1,D1:D2)'] },
+ },
+ },
+ }, testBed.sheetData as never);
+
+ expect(result[testBed.unitId]?.[testBed.sheetId]?.[0]?.[4]).toEqual([
+ { value: [[7], [0]], formula: '=SUMIFS(B1:B1,A1:A1,D1:D2)' },
+ ]);
+ });
+});