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.

fix(formula): index function handles base value object (#1692)

Dushusir1f0b7003f44e
diff --git a/packages/engine-formula/src/basics/object-class-type.ts b/packages/engine-formula/src/basics/object-class-type.ts
index b20d190e24..14bbfc21e5 100644
--- a/packages/engine-formula/src/basics/object-class-type.ts
+++ b/packages/engine-formula/src/basics/object-class-type.ts
@@ -47,6 +47,10 @@ export class ObjectClassType extends Disposable {
return false;
}
+ isArray() {
+ return false;
+ }
+
isValueObject() {
return false;
}
diff --git a/packages/engine-formula/src/engine/reference-object/base-reference-object.ts b/packages/engine-formula/src/engine/reference-object/base-reference-object.ts
index a3d3b5c499..4f3c28f173 100644
--- a/packages/engine-formula/src/engine/reference-object/base-reference-object.ts
+++ b/packages/engine-formula/src/engine/reference-object/base-reference-object.ts
@@ -94,7 +94,7 @@ export class BaseReferenceObject extends ObjectClassType {
isExceedRange() {
const { startRow, endRow, startColumn, endColumn } = this.getRangePosition();
- if (startRow < 0 || startColumn < 0 || endRow >= this.getRowCount() || endColumn >= this.getColumnCount()) {
+ if (startRow < 0 || startColumn < 0 || endRow >= this.getActiveSheetRowCount() || endColumn >= this.getActiveSheetColumnCount()) {
return true;
}
return false;
@@ -127,11 +127,11 @@ export class BaseReferenceObject extends ObjectClassType {
}
if (Number.isNaN(endRow)) {
- endRow = this.getRowCount() - 1;
+ endRow = this.getActiveSheetRowCount() - 1;
}
if (Number.isNaN(endColumn)) {
- endColumn = this.getColumnCount() - 1;
+ endColumn = this.getActiveSheetColumnCount() - 1;
}
return {
@@ -324,14 +324,22 @@ export class BaseReferenceObject extends ObjectClassType {
this._numfmtItemData = numfmtItemData;
}
- getRowCount() {
+ getActiveSheetRowCount() {
return this.getCurrentActiveSheetData().rowCount;
}
- getColumnCount() {
+ getActiveSheetColumnCount() {
return this.getCurrentActiveSheetData().columnCount;
}
+ getRowCount() {
+ return this._rangeData.endRow - this._rangeData.startRow + 1;
+ }
+
+ getColumnCount() {
+ return this._rangeData.endColumn - this._rangeData.startColumn + 1;
+ }
+
getRowData() {
return this.getCurrentActiveSheetData().rowData;
}
diff --git a/packages/engine-formula/src/engine/utils/__tests__/object-covert.spec.ts b/packages/engine-formula/src/engine/utils/__tests__/object-covert.spec.ts
deleted file mode 100644
index 70ae462865..0000000000
--- a/packages/engine-formula/src/engine/utils/__tests__/object-covert.spec.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import { describe, expect, it } from 'vitest';
-
-import { convertTonNumber } from '../object-covert';
-import { BooleanValueObject } from '../../value-object/primitive-object';
-
-describe('Test object cover', () => {
- it('Function convertTonNumber', () => {
- expect(convertTonNumber(BooleanValueObject.create(true)).getValue()).toBe(1);
- expect(convertTonNumber(BooleanValueObject.create(false)).getValue()).toBe(0);
- });
-});
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
new file mode 100644
index 0000000000..2f44cd38f6
--- /dev/null
+++ b/packages/engine-formula/src/engine/utils/__tests__/value-object.spec.ts
@@ -0,0 +1,58 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import { cellToRange } from '@univerjs/core';
+import { convertTonNumber, isSingleValueObject } from '../value-object';
+import { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from '../../value-object/primitive-object';
+import { ErrorValueObject } from '../../value-object/base-value-object';
+import { ErrorType } from '../../../basics/error-type';
+import { ArrayValueObject } from '../../value-object/array-value-object';
+import { CellReferenceObject } from '../../reference-object/cell-reference-object';
+import { RowReferenceObject } from '../../reference-object/row-reference-object';
+import { ColumnReferenceObject } from '../../reference-object/column-reference-object';
+import { RangeReferenceObject } from '../../reference-object/range-reference-object';
+
+describe('Test object cover', () => {
+ it('Function convertTonNumber', () => {
+ expect(convertTonNumber(BooleanValueObject.create(true)).getValue()).toBe(1);
+ expect(convertTonNumber(BooleanValueObject.create(false)).getValue()).toBe(0);
+ });
+
+ it('Function isSingleValueObject', () => {
+ expect(isSingleValueObject(BooleanValueObject.create(true))).toBe(true);
+ expect(isSingleValueObject(BooleanValueObject.create(false))).toBe(true);
+ expect(isSingleValueObject(NumberValueObject.create(1))).toBe(true);
+ expect(isSingleValueObject(StringValueObject.create('Univer'))).toBe(true);
+ expect(isSingleValueObject(NullValueObject.create())).toBe(true);
+ expect(isSingleValueObject(ErrorValueObject.create(ErrorType.VALUE))).toBe(true);
+
+ expect(isSingleValueObject(ArrayValueObject.create(/*ts*/ `{
+ 1, 3;
+ 8, 7
+ }`))).toBe(false);
+ expect(isSingleValueObject(ArrayValueObject.create(/*ts*/ `{
+ 1
+ }`))).toBe(true);
+
+ expect(isSingleValueObject(new CellReferenceObject('A1'))).toBe(true);
+ expect(isSingleValueObject(new RowReferenceObject('1:1'))).toBe(false);
+ expect(isSingleValueObject(new ColumnReferenceObject('A:A'))).toBe(false);
+ expect(isSingleValueObject(new RangeReferenceObject(cellToRange(0, 1)))).toBe(true);
+ expect(isSingleValueObject(new RangeReferenceObject({ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }))).toBe(false);
+ });
+});
diff --git a/packages/engine-formula/src/engine/utils/array-object.ts b/packages/engine-formula/src/engine/utils/array-object.ts
index 2d5446e554..07a413bf4a 100644
--- a/packages/engine-formula/src/engine/utils/array-object.ts
+++ b/packages/engine-formula/src/engine/utils/array-object.ts
@@ -78,14 +78,16 @@ export function expandArrayValueObject(rowCount: number, columnCount: number, va
export function createNewArray(
result: BaseValueObject[][],
rowCount: number,
- columnCount: number
+ columnCount: number,
+ unitId = '',
+ sheetId = ''
) {
const arrayValueObjectData: IArrayValueObject = {
calculateValueList: result,
rowCount,
columnCount,
- unitId: '',
- sheetId: '',
+ unitId,
+ sheetId,
row: -1,
column: -1,
};
diff --git a/packages/engine-formula/src/engine/utils/object-covert.ts b/packages/engine-formula/src/engine/utils/object-covert.ts
deleted file mode 100644
index a19fca15db..0000000000
--- a/packages/engine-formula/src/engine/utils/object-covert.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { BaseValueObject } from '../value-object/base-value-object';
-import { NumberValueObject } from '../value-object/primitive-object';
-
-export function convertTonNumber(valueObject: BaseValueObject) {
- const currentValue = valueObject.getValue();
- let result = 0;
- if (currentValue) {
- result = 1;
- }
- return NumberValueObject.create(result);
-}
diff --git a/packages/engine-formula/src/engine/utils/value-object.ts b/packages/engine-formula/src/engine/utils/value-object.ts
new file mode 100644
index 0000000000..168edabfb6
--- /dev/null
+++ b/packages/engine-formula/src/engine/utils/value-object.ts
@@ -0,0 +1,55 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { BaseReferenceObject, FunctionVariantType } from '../reference-object/base-reference-object';
+import type { ArrayValueObject } from '../value-object/array-value-object';
+import type { BaseValueObject } from '../value-object/base-value-object';
+import { NumberValueObject } from '../value-object/primitive-object';
+
+export function convertTonNumber(valueObject: BaseValueObject) {
+ const currentValue = valueObject.getValue();
+ let result = 0;
+ if (currentValue) {
+ result = 1;
+ }
+ return NumberValueObject.create(result);
+}
+
+export function isSingleValueObject(valueObject: FunctionVariantType) {
+ if (valueObject.isArray() && (valueObject as ArrayValueObject).getRowCount() === 1 && (valueObject as ArrayValueObject).getColumnCount() === 1) {
+ return true;
+ }
+
+ if (valueObject.isReferenceObject()) {
+ if ((valueObject as BaseReferenceObject).isCell()) {
+ return true;
+ }
+
+ if ((valueObject as BaseReferenceObject).getRowCount() === 1 && (valueObject as BaseReferenceObject).getColumnCount() === 1) {
+ return true;
+ }
+
+ return false;
+ }
+
+ valueObject = valueObject as BaseValueObject;
+
+ if (valueObject.isString() || valueObject.isNumber() || valueObject.isBoolean() || valueObject.isError() || valueObject.isNull()) {
+ return true;
+ }
+
+ return false;
+}
diff --git a/packages/engine-formula/src/engine/value-object/base-value-object.ts b/packages/engine-formula/src/engine/value-object/base-value-object.ts
index bb1f0afe9c..44faf35313 100644
--- a/packages/engine-formula/src/engine/value-object/base-value-object.ts
+++ b/packages/engine-formula/src/engine/value-object/base-value-object.ts
@@ -76,10 +76,6 @@ export class BaseValueObject extends ObjectClassType {
return false;
}
- isArray() {
- return false;
- }
-
isString() {
return false;
}
diff --git a/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts b/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts
index b6c0bb473b..0ca8cc2171 100644
--- a/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts
+++ b/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts
@@ -53,6 +53,9 @@ import { FunctionService, IFunctionService } from '../../services/function.servi
import { IOtherFormulaManagerService, OtherFormulaManagerService } from '../../services/other-formula-manager.service';
import { FormulaRuntimeService, IFormulaRuntimeService } from '../../services/runtime.service';
import { ISuperTableService, SuperTableService } from '../../services/super-table.service';
+import type { BaseValueObject, ErrorValueObject } from '../../engine/value-object/base-value-object';
+import type { BaseReferenceObject, FunctionVariantType } from '../../engine/reference-object/base-reference-object';
+import type { ArrayValueObject } from '../../engine/value-object/array-value-object';
const getTestWorkbookData = (): IWorkbookData => {
return {
@@ -231,3 +234,14 @@ export function createFunctionTestBed(workbookConfig?: IWorkbookData, dependenci
sheetData,
};
}
+
+export function getObjectValue(result: FunctionVariantType) {
+ if ((result as ErrorValueObject).isError()) {
+ return (result as ErrorValueObject).getValue();
+ } else if ((result as BaseReferenceObject).isReferenceObject()) {
+ return (result as BaseReferenceObject).toArrayValueObject().toValue();
+ } else if ((result as ArrayValueObject).isArray()) {
+ return (result as ArrayValueObject).toValue();
+ }
+ return (result as BaseValueObject).getValue();
+}
diff --git a/packages/engine-formula/src/functions/base-function.ts b/packages/engine-formula/src/functions/base-function.ts
index 4b9f7939b5..08084cc08f 100644
--- a/packages/engine-formula/src/functions/base-function.ts
+++ b/packages/engine-formula/src/functions/base-function.ts
@@ -26,7 +26,7 @@ import { ArrayOrderSearchType } from '../engine/utils/compare';
import type { ArrayValueObject } from '../engine/value-object/array-value-object';
import { type BaseValueObject, ErrorValueObject } from '../engine/value-object/base-value-object';
import { NullValueObject, NumberValueObject, type PrimitiveValueType } from '../engine/value-object/primitive-object';
-import { convertTonNumber } from '../engine/utils/object-covert';
+import { convertTonNumber } from '../engine/utils/value-object';
import { createNewArray } from '../engine/utils/array-object';
import { serializeRangeToRefString } from '../engine/utils/reference';
import { REFERENCE_REGEX_SINGLE_COLUMN, REFERENCE_REGEX_SINGLE_ROW, REFERENCE_SINGLE_RANGE_REGEX } from '../basics/regex';
diff --git a/packages/engine-formula/src/functions/lookup/index/__test__/index.spec.ts b/packages/engine-formula/src/functions/lookup/index/__test__/index.spec.ts
index ee2ecd4cba..57a1f63883 100644
--- a/packages/engine-formula/src/functions/lookup/index/__test__/index.spec.ts
+++ b/packages/engine-formula/src/functions/lookup/index/__test__/index.spec.ts
@@ -27,13 +27,10 @@ import { Interpreter } from '../../../../engine/interpreter/interpreter';
import { IFormulaCurrentConfigService } from '../../../../services/current-data.service';
import { IFunctionService } from '../../../../services/function.service';
import { IFormulaRuntimeService } from '../../../../services/runtime.service';
-import { createFunctionTestBed } from '../../../__tests__/create-function-test-bed';
+import { createFunctionTestBed, getObjectValue } from '../../../__tests__/create-function-test-bed';
import { FUNCTION_NAMES_LOOKUP } from '../../function-names';
-import type { BaseValueObject, ErrorValueObject } from '../../../../engine/value-object/base-value-object';
-import type { ArrayValueObject } from '../../../../engine/value-object/array-value-object';
import { Index } from '..';
import { ErrorType } from '../../../../basics/error-type';
-import type { BaseReferenceObject } from '../../../../engine/reference-object/base-reference-object';
const getTestWorkbookData = (): IWorkbookData => {
return {
@@ -201,14 +198,7 @@ describe('Test index', () => {
const result = await interpreter.executeAsync(astNode as BaseAstNode);
- if ((result as ErrorValueObject).isError()) {
- return (result as ErrorValueObject).getValue();
- } else if ((result as BaseReferenceObject).isReferenceObject()) {
- return (result as BaseReferenceObject).toArrayValueObject().toValue();
- } else if ((result as ArrayValueObject).isArray()) {
- return (result as ArrayValueObject).toValue();
- }
- return (result as BaseValueObject).getValue();
+ return getObjectValue(result);
};
});
@@ -729,5 +719,23 @@ describe('Test index', () => {
expect(result).toStrictEqual([['Tom', ErrorType.VALUE, 'Tom', 'Tom', 'Tom', 'Tom'], ['Tom', ErrorType.REF, 'Sarah', ErrorType.VALUE, ErrorType.VALUE, 'Tom'], [ErrorType.NA, ErrorType.NA, ErrorType.NA, ErrorType.NA, ErrorType.NA, ErrorType.NA]]);
});
});
+ describe('Single base value object as referenceObject', () => {
+ it('Row number 1, column number 1', async () => {
+ // number
+ let result = await calculate('=INDEX(1,1,1)');
+
+ expect(result).toBe(1);
+
+ // boolean
+ result = await calculate('=INDEX(TRUE,1,1)');
+
+ expect(result).toBe(true);
+
+ // string
+ result = await calculate('=INDEX("Univer",1,1)');
+
+ expect(result).toBe('Univer');
+ });
+ });
// supports array string
});
diff --git a/packages/engine-formula/src/functions/lookup/index/index.ts b/packages/engine-formula/src/functions/lookup/index/index.ts
index eef92ce9e2..cf8eff13f5 100644
--- a/packages/engine-formula/src/functions/lookup/index/index.ts
+++ b/packages/engine-formula/src/functions/lookup/index/index.ts
@@ -15,7 +15,7 @@
*/
import { ErrorType } from '../../../basics/error-type';
-import type { BaseReferenceObject } from '../../../engine/reference-object/base-reference-object';
+import type { BaseReferenceObject, FunctionVariantType } from '../../../engine/reference-object/base-reference-object';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
@@ -27,15 +27,11 @@ import { BaseFunction } from '../../base-function';
*
* =INDEX(A2:A5,2,1):A1 same as =A1:A3
*
- * OPTIMIZE: maybe we can remove some unknown type
*/
export class Index extends BaseFunction {
override needsReferenceObject = true;
- override calculate(referenceObject: BaseValueObject, rowNum: BaseValueObject, columnNum?: BaseValueObject, areaNum?: BaseValueObject) {
- // covert to real type
- const reference = referenceObject as unknown as BaseReferenceObject;
-
+ override calculate(reference: FunctionVariantType, rowNum: FunctionVariantType, columnNum?: FunctionVariantType, areaNum?: FunctionVariantType) {
if (reference == null) {
return ErrorValueObject.create(ErrorType.NA);
}
@@ -56,13 +52,19 @@ export class Index extends BaseFunction {
return areaNum;
}
- if (!(reference.isRange())) {
- return ErrorValueObject.create(ErrorType.REF);
- }
+ let referenceRowCount = 0;
+ let referenceColumnCount = 0;
- const { startRow, endRow, startColumn, endColumn } = reference.getRangeData();
- const referenceRowCount = endRow - startRow + 1;
- const referenceColumnCount = endColumn - startColumn + 1;
+ if (reference.isValueObject()) {
+ referenceRowCount = 1;
+ referenceColumnCount = 1;
+ } else if (reference.isReferenceObject()) {
+ const { startRow, endRow, startColumn, endColumn } = (reference as BaseReferenceObject).getRangeData();
+ referenceRowCount = endRow - startRow + 1;
+ referenceColumnCount = endColumn - startColumn + 1;
+ } else {
+ return ErrorValueObject.create(ErrorType.VALUE);
+ }
// When there is only one row, the rowNum is considered to be the column number.
// =INDEX(A6:B6,2) equals =INDEX(A6:B6,1,2)
@@ -77,15 +79,15 @@ export class Index extends BaseFunction {
areaNum = areaNum ?? NumberValueObject.create(1);
if (rowNum.isReferenceObject()) {
- rowNum = (rowNum as unknown as BaseReferenceObject).toArrayValueObject();
+ rowNum = (rowNum as BaseReferenceObject).toArrayValueObject();
}
if (columnNum.isReferenceObject()) {
- columnNum = (columnNum as unknown as BaseReferenceObject).toArrayValueObject();
+ columnNum = (columnNum as BaseReferenceObject).toArrayValueObject();
}
if (areaNum.isReferenceObject()) {
- areaNum = (areaNum as unknown as BaseReferenceObject).toArrayValueObject();
+ areaNum = (areaNum as BaseReferenceObject).toArrayValueObject();
}
// get max row length
@@ -102,6 +104,10 @@ export class Index extends BaseFunction {
areaNum.isArray() ? (areaNum as ArrayValueObject).getColumnCount() : 1
);
+ rowNum = rowNum as BaseValueObject;
+ columnNum = columnNum as BaseValueObject;
+ areaNum = areaNum as BaseValueObject;
+
// If maxRowLength and maxColumnLength are both 1, pick the value from the reference array
// Otherwise, filter the results from the reference according to the specified rowNum/columnNum/areaNum, take the upper left corner cell value of each result array, and then form an array with maxRowLength row number and maxColumnLength column number.
if (maxRowLength === 1 && maxColumnLength === 1) {
@@ -126,7 +132,7 @@ export class Index extends BaseFunction {
}
}
- private _calculateSingleCell(reference: BaseReferenceObject, rowNum: BaseValueObject, columnNum: BaseValueObject, areaNum: BaseValueObject) {
+ private _calculateSingleCell(reference: FunctionVariantType, rowNum: BaseValueObject, columnNum: BaseValueObject, areaNum: BaseValueObject) {
if (rowNum.isError()) {
return rowNum;
}
@@ -158,7 +164,13 @@ export class Index extends BaseFunction {
return ErrorValueObject.create(ErrorType.VALUE);
}
- return this._getReferenceObject(reference, rowNumberValue, columnNumberValue, areaNumberValue);
+ if (reference.isReferenceObject()) {
+ return this._getReferenceObject(reference as BaseReferenceObject, rowNumberValue, columnNumberValue, areaNumberValue);
+ } else if (reference.isValueObject() && rowNumberValue === 1 && columnNumberValue === 1) {
+ return reference;
+ } else {
+ return ErrorValueObject.create(ErrorType.REF);
+ }
}
private _getNumberValue(numberValueObject?: BaseValueObject) {
diff --git a/packages/engine-formula/src/functions/lookup/offset/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/offset/__tests__/index.spec.ts
index 578e80e617..665ca5c061 100644
--- a/packages/engine-formula/src/functions/lookup/offset/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/lookup/offset/__tests__/index.spec.ts
@@ -17,21 +17,122 @@
import type { Injector } from '@wendellhu/redi';
import { beforeEach, describe, expect, it } from 'vitest';
+import type { IWorkbookData } from '@univerjs/core';
+import { CellValueType, LocaleType } from '@univerjs/core';
import { Lexer } from '../../../../engine/analysis/lexer';
import type { LexerNode } from '../../../../engine/analysis/lexer-node';
import { AstTreeBuilder } from '../../../../engine/analysis/parser';
import type { BaseAstNode } from '../../../../engine/ast-node/base-ast-node';
import { Interpreter } from '../../../../engine/interpreter/interpreter';
-import type { BaseReferenceObject } from '../../../../engine/reference-object/base-reference-object';
import { IFormulaCurrentConfigService } from '../../../../services/current-data.service';
import { IFunctionService } from '../../../../services/function.service';
import { IFormulaRuntimeService } from '../../../../services/runtime.service';
-import { createFunctionTestBed } from '../../../__tests__/create-function-test-bed';
+import { createFunctionTestBed, getObjectValue } from '../../../__tests__/create-function-test-bed';
import { FUNCTION_NAMES_LOOKUP } from '../../function-names';
import { Offset } from '..';
-import type { BaseValueObject, ErrorValueObject } from '../../../../engine/value-object/base-value-object';
import { ErrorType } from '../../../../basics/error-type';
-import type { ArrayValueObject } from '../../../../engine/value-object/array-value-object';
+
+const getTestWorkbookData = (): IWorkbookData => {
+ return {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ cellData: {
+ 0: {
+ 0: {
+ v: 1,
+ t: CellValueType.NUMBER,
+ },
+ 1: {
+ v: 2,
+ t: CellValueType.NUMBER,
+ },
+ 2: {
+ v: -1,
+ t: CellValueType.NUMBER,
+ },
+ 3: {
+ v: -1,
+ t: CellValueType.NUMBER,
+ },
+ 4: {
+ v: ErrorType.NAME,
+ t: CellValueType.STRING,
+ },
+ },
+ 1: {
+ 0: {
+ v: 3,
+ t: CellValueType.NUMBER,
+ },
+ 1: {
+ v: 4,
+ t: CellValueType.NUMBER,
+ },
+ 2: {
+ v: 'B2',
+ t: CellValueType.STRING,
+ },
+ 3: {
+ v: 'R2C2',
+ t: CellValueType.STRING,
+ },
+ },
+ 2: {
+ 0: {
+ v: 1,
+ t: CellValueType.NUMBER,
+ },
+ 1: {
+ v: ' ',
+ t: CellValueType.STRING,
+ },
+ 2: {
+ v: 1.23,
+ t: CellValueType.NUMBER,
+ },
+ 3: {
+ v: true,
+ t: CellValueType.BOOLEAN,
+ },
+ 4: {
+ v: false,
+ t: CellValueType.BOOLEAN,
+ },
+ },
+ 3: {
+ 0: {
+ v: 0,
+ t: CellValueType.NUMBER,
+ },
+ 1: {
+ v: '100',
+ t: CellValueType.STRING,
+ },
+ 2: {
+ v: '2.34',
+ t: CellValueType.STRING,
+ },
+ 3: {
+ v: 'test',
+ t: CellValueType.STRING,
+ },
+ 4: {
+ v: -3,
+ t: CellValueType.NUMBER,
+ },
+ },
+ },
+ },
+ },
+ locale: LocaleType.ZH_CN,
+ name: '',
+ sheetOrder: [],
+ styles: {},
+ };
+};
describe('Test offset', () => {
let get: Injector['get'];
@@ -41,7 +142,7 @@ describe('Test offset', () => {
let calculate: (formula: string) => Promise<(string | number | boolean | null)[][] | string | number | boolean>;
beforeEach(() => {
- const testBed = createFunctionTestBed();
+ const testBed = createFunctionTestBed(getTestWorkbookData());
get = testBed.get;
@@ -92,18 +193,11 @@ describe('Test offset', () => {
const result = await interpreter.executeAsync(astNode as BaseAstNode);
- if ((result as ErrorValueObject).isError()) {
- return (result as ErrorValueObject).getValue();
- } else if ((result as BaseReferenceObject).isReferenceObject()) {
- return (result as BaseReferenceObject).toArrayValueObject().toValue();
- } else if ((result as ArrayValueObject).isArray()) {
- return (result as ArrayValueObject).toValue();
- }
- return (result as BaseValueObject).getValue();
+ return getObjectValue(result);
};
});
- describe('Offset', () => {
+ describe('Offset, reference is single reference value object', () => {
it('Normal single cell', async () => {
const result = await calculate('=OFFSET(A1,1,0,1,1)');
@@ -139,5 +233,59 @@ describe('Test offset', () => {
expect(result).toStrictEqual([[4, 'B2']]);
});
+
+ it('Rows is single reference object', async () => {
+ const result = await calculate('=OFFSET(A1,A1,1,1,1)');
+
+ expect(result).toStrictEqual([[4]]);
+ });
+
+ it('Rows is array value object, positive and negative numbers', async () => {
+ const result = await calculate('=OFFSET(A1,B1:C1,1)');
+
+ expect(result).toStrictEqual([[ErrorType.VALUE, ErrorType.REF]]);
+ });
+
+ it('Rows is array value object, Columns is array value object', async () => {
+ const result = await calculate('=OFFSET(A1,A1:B1,A1:A2,1,1)');
+
+ expect(result).toStrictEqual([[ErrorType.VALUE, ErrorType.VALUE], [ErrorType.VALUE, ErrorType.VALUE]]);
+ });
+
+ it('Rows is array value object, Columns is array value object, ref error', async () => {
+ const result = await calculate('=OFFSET(A1,A1:A2,D1:E1,1,1)');
+
+ expect(result).toStrictEqual([[ErrorType.REF, ErrorType.NAME], [ErrorType.REF, ErrorType.NAME]]);
+ });
+
+ it('Rows is array value object, Columns is array value object, ref error, height is array, width is array', async () => {
+ const result = await calculate('=OFFSET(A1,A1:A2,D1:E1,I4:I6,J4:L4)');
+
+ expect(result).toStrictEqual([[ErrorType.REF, ErrorType.NAME, ErrorType.NA], [ErrorType.REF, ErrorType.NAME, ErrorType.NA], [ErrorType.NA, ErrorType.NA, ErrorType.NA]]);
+ });
+ });
+
+ describe('Offset, reference is base value object', () => {
+ it('Rows single number, columns single number', async () => {
+ let result = await calculate('=OFFSET(1,1,1)');
+
+ expect(result).toBe(ErrorType.VALUE);
+
+ result = await calculate('=OFFSET("Univer",1,1)');
+
+ expect(result).toBe(ErrorType.VALUE);
+
+ result = await calculate('=OFFSET(TRUE,1,1)');
+
+ expect(result).toBe(ErrorType.VALUE);
+ });
+ });
+
+ describe('Offset, reference is array value object', () => {
+ it('Rows single number, columns single number', async () => {
+ const result = await calculate('=OFFSET(A1:B2,1,1)');
+
+ expect(result).toStrictEqual([[4, 'B2'], [' ', 1.23]]);
+ });
});
});
diff --git a/packages/engine-formula/src/functions/lookup/offset/index.ts b/packages/engine-formula/src/functions/lookup/offset/index.ts
index efcaf5bf71..a15ee4fa9c 100644
--- a/packages/engine-formula/src/functions/lookup/offset/index.ts
+++ b/packages/engine-formula/src/functions/lookup/offset/index.ts
@@ -15,25 +15,24 @@
*/
import { ErrorType } from '../../../basics/error-type';
-import type { BaseReferenceObject } from '../../../engine/reference-object/base-reference-object';
-import type { RangeReferenceObject } from '../../../engine/reference-object/range-reference-object';
+import type { BaseReferenceObject, FunctionVariantType } from '../../../engine/reference-object/base-reference-object';
+import { expandArrayValueObject } from '../../../engine/utils/array-object';
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
+import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
export class Offset extends BaseFunction {
override needsReferenceObject = true;
override calculate(
- referenceObject: BaseValueObject,
- rows: BaseValueObject,
- columns: BaseValueObject,
- height?: BaseValueObject,
- width?: BaseValueObject
+ reference: FunctionVariantType,
+ rows: FunctionVariantType,
+ columns: FunctionVariantType,
+ height?: FunctionVariantType,
+ width?: FunctionVariantType
) {
- // covert to real type
- const reference = referenceObject as unknown as RangeReferenceObject;
-
if (reference == null || rows == null || columns == null) {
return ErrorValueObject.create(ErrorType.NA);
}
@@ -62,41 +61,111 @@ export class Offset extends BaseFunction {
return ErrorValueObject.create(ErrorType.VALUE);
}
- const { startRow: row, endRow: referenceEndRow, startColumn: column, endColumn: referenceEndColumn } = reference.getRangeData();
+ reference = reference as BaseReferenceObject;
+
+ const rowCount = reference.getRowCount();
+ const columnCount = reference.getColumnCount();
if (rows.isReferenceObject()) {
- rows = (rows as unknown as BaseReferenceObject).toArrayValueObject();
+ rows = (rows as BaseReferenceObject).toArrayValueObject();
}
if (columns.isReferenceObject()) {
- columns = (columns as unknown as BaseReferenceObject).toArrayValueObject();
- }
+ columns = (columns as BaseReferenceObject).toArrayValueObject();
+ }
+
+ // The default row height is the row height of reference.
+ if (!height) {
+ height = NumberValueObject.create(rowCount);
+ } else if (height.isReferenceObject()) {
+ height = (height as BaseReferenceObject).toArrayValueObject();
+ }
+
+ // The default column width is the column width of reference.
+ if (!width) {
+ width = NumberValueObject.create(columnCount);
+ } else if (width.isReferenceObject()) {
+ width = (width as BaseReferenceObject).toArrayValueObject();
+ }
+
+ // If rows/columns/height/width is a range, it needs to be extended
+ // get max row length
+ const maxRowLength = Math.max(
+ rows.isArray() ? (rows as ArrayValueObject).getRowCount() : 1,
+ columns.isArray() ? (columns as ArrayValueObject).getRowCount() : 1,
+ height.isArray() ? (height as ArrayValueObject).getRowCount() : 1,
+ width.isArray() ? (width as ArrayValueObject).getRowCount() : 1
+ );
+
+ // get max column length
+ const maxColumnLength = Math.max(
+ rows.isArray() ? (rows as ArrayValueObject).getColumnCount() : 1,
+ columns.isArray() ? (columns as ArrayValueObject).getColumnCount() : 1,
+ height.isArray() ? (height as ArrayValueObject).getColumnCount() : 1,
+ width.isArray() ? (width as ArrayValueObject).getColumnCount() : 1
+ );
+
+ rows = rows as BaseValueObject;
+ columns = columns as BaseValueObject;
+ height = height as BaseValueObject;
+ width = width as BaseValueObject;
+
+ // If any parameter of row/columns/height/width is an array(not single cell reference), an error will be reported, and the error report also needs to be expanded and specific error information is required. Otherwise, calculate the offset.
+ if (maxRowLength === 1 && maxColumnLength === 1) {
+ return this._handleSingleObject(reference, rows, columns, height, width);
+ }
+
+ const rowsArray = expandArrayValueObject(maxRowLength, maxColumnLength, rows, ErrorValueObject.create(ErrorType.NA));
+ const columnsArray = expandArrayValueObject(maxRowLength, maxColumnLength, columns, ErrorValueObject.create(ErrorType.NA));
+ const heightArray = expandArrayValueObject(maxRowLength, maxColumnLength, height, ErrorValueObject.create(ErrorType.NA));
+ const widthArray = expandArrayValueObject(maxRowLength, maxColumnLength, width, ErrorValueObject.create(ErrorType.NA));
+
+ return rowsArray.mapValue((rowsValue, rowIndex, columnIndex) => {
+ const columnsValue = columnsArray.get(rowIndex, columnIndex) as BaseValueObject;
+ const heightValue = heightArray.get(rowIndex, columnIndex) as BaseValueObject;
+ const widthValue = widthArray.get(rowIndex, columnIndex) as BaseValueObject;
+
+ if (rowsValue.isError()) {
+ return rowsValue;
+ }
+
+ if (columnsValue.isError()) {
+ return columnsValue;
+ }
+
+ if (heightValue.isError()) {
+ return heightValue;
+ }
+
+ if (widthValue.isError()) {
+ return widthValue;
+ }
+
+ // Ensure that the callback function returns a BaseValueObject
+ return this._handleSingleObject(reference, rowsValue, columnsValue, heightValue, widthValue, true) as BaseValueObject;
+ });
+ }
+
+ private _handleSingleObject(reference: BaseReferenceObject, rowsValue: BaseValueObject, columnsValue: BaseValueObject, heightValue: BaseValueObject, widthValue: BaseValueObject, isReportError = false) {
+ const { startRow: referenceStartRow, startColumn: referenceStartColumn } = reference.getRangeData();
- const rowOffset = this.getIndexNumValue(rows);
- const columnOffset = this.getIndexNumValue(columns);
+ const rowOffset = this.getIndexNumValue(rowsValue);
+ const columnOffset = this.getIndexNumValue(columnsValue);
if (typeof rowOffset !== 'number' || typeof columnOffset !== 'number') {
return ErrorValueObject.create(ErrorType.VALUE);
}
- const targetRow = row + rowOffset;
- const targetColumn = column + columnOffset;
+ const targetRow = referenceStartRow + rowOffset;
+ const targetColumn = referenceStartColumn + columnOffset;
// Excel has a limit on the number of rows and columns: targetRow > 1048576 || targetColumn > 16384, Univer has no limit
if (targetRow < 0 || targetColumn < 0) {
return ErrorValueObject.create(ErrorType.REF);
}
- if (height?.isReferenceObject()) {
- height = (height as unknown as BaseReferenceObject).toArrayValueObject();
- }
-
- if (width?.isReferenceObject()) {
- width = (width as unknown as BaseReferenceObject).toArrayValueObject();
- }
-
- const heightCount = (height && this.getIndexNumValue(height)) ?? 1;
- const widthCount = (width && this.getIndexNumValue(width)) ?? 1;
+ const heightCount = this.getIndexNumValue(heightValue);
+ const widthCount = this.getIndexNumValue(widthValue);
if (typeof heightCount !== 'number' || typeof widthCount !== 'number') {
return ErrorValueObject.create(ErrorType.VALUE);
@@ -114,6 +183,10 @@ export class Offset extends BaseFunction {
return ErrorValueObject.create(ErrorType.REF);
}
+ if (isReportError) {
+ return ErrorValueObject.create(ErrorType.VALUE);
+ }
+
const startRow = targetRow < targetRowWithHeight ? targetRow : targetRowWithHeight;
const startColumn = targetColumn < targetColumnWithWidth ? targetColumn : targetColumnWithWidth;
const endRow = targetRow > targetRowWithHeight ? targetRow : targetRowWithHeight;
diff --git a/packages/engine-formula/src/functions/lookup/vlookup/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/vlookup/__tests__/index.spec.ts
index 9d3ed2bb30..66a0da6af0 100644
--- a/packages/engine-formula/src/functions/lookup/vlookup/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/lookup/vlookup/__tests__/index.spec.ts
@@ -19,9 +19,10 @@ import { describe, expect, it } from 'vitest';
import { ErrorType } from '../../../../basics/error-type';
import { ArrayValueObject } from '../../../../engine/value-object/array-value-object';
import type { BaseValueObject } from '../../../../engine/value-object/base-value-object';
-import { NumberValueObject } from '../../../../engine/value-object/primitive-object';
+import { NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';
import { FUNCTION_NAMES_LOOKUP } from '../../function-names';
import { Vlookup } from '..';
+import { getObjectValue } from '../../../__tests__/create-function-test-bed';
const arrayValueObject1 = ArrayValueObject.create(/*ts*/ `{
1, "First";
@@ -51,6 +52,29 @@ const matchArrayValueObject = ArrayValueObject.create(/*ts*/ `{
8, 7
}`);
+const matchArrayValueObject2 = ArrayValueObject.create(/*ts*/ `{
+ 1;
+ 4;
+ 8
+}`);
+
+const colIndexNumArrayValueObject = ArrayValueObject.create(/*ts*/ `{
+ 1, 2
+}`);
+
+const colIndexNumArrayValueObject2 = ArrayValueObject.create(/*ts*/ `{
+ 1, 2;
+ 3, 4
+}`);
+
+const colIndexNumArrayValueObject3 = ArrayValueObject.create(/*ts*/ `{
+ 2, 1
+}`);
+
+const rangeLookupArrayValueObject = ArrayValueObject.create(/*ts*/ `{
+ 0, 1, 0, 1
+}`);
+
describe('Test vlookup', () => {
const textFunction = new Vlookup(FUNCTION_NAMES_LOOKUP.VLOOKUP);
@@ -62,7 +86,7 @@ describe('Test vlookup', () => {
NumberValueObject.create(2),
NumberValueObject.create(0)
) as BaseValueObject;
- expect(resultObject.getValue().toString()).toBe('Second');
+ expect(getObjectValue(resultObject)).toStrictEqual([['Second']]);
});
it('Search eight', async () => {
@@ -72,7 +96,7 @@ describe('Test vlookup', () => {
NumberValueObject.create(2),
NumberValueObject.create(0)
) as BaseValueObject;
- expect(resultObject.getValue().toString()).toBe('Eighth');
+ expect(getObjectValue(resultObject)).toStrictEqual([['Eighth']]);
});
it('Exceeding columns', async () => {
@@ -82,7 +106,7 @@ describe('Test vlookup', () => {
NumberValueObject.create(3),
NumberValueObject.create(0)
) as BaseValueObject;
- expect(resultObject.getValue().toString()).toBe(ErrorType.VALUE);
+ expect(getObjectValue(resultObject)).toStrictEqual([[ErrorType.REF]]);
});
it('Not match', async () => {
@@ -92,22 +116,119 @@ describe('Test vlookup', () => {
NumberValueObject.create(2),
NumberValueObject.create(0)
) as BaseValueObject;
- expect(resultObject.getValue().toString()).toBe(ErrorType.NA);
+ expect(getObjectValue(resultObject)).toStrictEqual([[ErrorType.NA]]);
});
- it('array', async () => {
+ it('LookupValue is array, colIndexNum is single cell', async () => {
const resultObject = textFunction.calculate(
matchArrayValueObject.clone(),
arrayValueObject1.clone(),
NumberValueObject.create(2),
NumberValueObject.create(0)
) as BaseValueObject;
- expect((resultObject as ArrayValueObject).toValue()).toStrictEqual([
+ expect(getObjectValue(resultObject)).toStrictEqual([
['First', 'Third'],
['Fourth', 'Sixth'],
['Eighth', 'Seventh'],
]);
});
+
+ it('LookupValue is single cell, colIndexNum is array', async () => {
+ const resultObject = textFunction.calculate(
+ NumberValueObject.create(2),
+ arrayValueObject1.clone(),
+ colIndexNumArrayValueObject.clone(),
+ NumberValueObject.create(0)
+ ) as BaseValueObject;
+ expect(getObjectValue(resultObject)).toStrictEqual([
+ [2, 'Second'],
+ ]);
+ });
+
+ it('LookupValue is single cell, colIndexNum is array and gets colIndexNum error', async () => {
+ const resultObject = textFunction.calculate(
+ NumberValueObject.create(2),
+ arrayValueObject1.clone(),
+ colIndexNumArrayValueObject2.clone(),
+ NumberValueObject.create(0)
+ ) as BaseValueObject;
+ expect(getObjectValue(resultObject)).toStrictEqual(ErrorType.REF);
+ });
+
+ it('LookupValue is single cell, colIndexNum is array and gets lookupValue error', async () => {
+ const resultObject = textFunction.calculate(
+ StringValueObject.create('lookupValue'),
+ arrayValueObject1.clone(),
+ ArrayValueObject.create(/*ts*/ `{
+ 3, 4;
+ }`),
+ NumberValueObject.create(0)
+ ) as BaseValueObject;
+ expect(getObjectValue(resultObject)).toStrictEqual(ErrorType.REF);
+ });
+
+ it('LookupValue is single cell, colIndexNum is array and gets rangeLookup error', async () => {
+ const resultObject = textFunction.calculate(
+ StringValueObject.create('lookupValue'),
+ arrayValueObject1.clone(),
+ colIndexNumArrayValueObject2.clone(),
+ StringValueObject.create('rangeLookup')
+ ) as BaseValueObject;
+ expect(getObjectValue(resultObject)).toStrictEqual(ErrorType.VALUE);
+ });
+
+ it('LookupValue is array, colIndexNum is array', async () => {
+ const resultObject = textFunction.calculate(
+ matchArrayValueObject.clone(),
+ arrayValueObject1.clone(),
+ colIndexNumArrayValueObject.clone(),
+ NumberValueObject.create(0)
+ ) as BaseValueObject;
+ expect(getObjectValue(resultObject)).toStrictEqual([
+ [1, 3],
+ [4, 6],
+ [8, 7],
+ ]);
+ });
+
+ it('LookupValue is array and gets error, colIndexNum is array and gets error', async () => {
+ const resultObject = textFunction.calculate(
+ ArrayValueObject.create(/*ts*/ `{
+ "Univer";
+ 2
+ }`),
+ arrayValueObject1.clone(),
+ ArrayValueObject.create(/*ts*/ `{
+ 3, 1
+ }`)
+ ) as BaseValueObject;
+ expect(getObjectValue(resultObject)).toStrictEqual([[ErrorType.REF], [ErrorType.REF]]);
+ });
+
+ it('LookupValue is array and gets error, colIndexNum is array and gets error,rangeLookup gets error', async () => {
+ const resultObject = textFunction.calculate(
+ ArrayValueObject.create(/*ts*/ `{
+ "Univer";
+ 2
+ }`),
+ arrayValueObject1.clone(),
+ ArrayValueObject.create(/*ts*/ `{
+ 3, 1
+ }`),
+ StringValueObject.create('rangeLookup')
+ ) as BaseValueObject;
+ expect(getObjectValue(resultObject)).toStrictEqual([[ErrorType.VALUE], [ErrorType.VALUE]]);
+ });
+
+ it('LookupValue is array, colIndexNum is array, rangeLookup is array', async () => {
+ const resultObject = textFunction.calculate(
+ matchArrayValueObject2.clone(),
+ arrayValueObject1.clone(),
+ colIndexNumArrayValueObject3.clone(),
+ rangeLookupArrayValueObject.clone()
+ ) as BaseValueObject;
+ expect(getObjectValue(resultObject)).toStrictEqual([['First', 'First', 'First', 'First'], ['Fourth', 'Fourth', 'Fourth', 'Fourth'], ['Eighth', 'Eighth', 'Eighth', 'Eighth']]);
+ });
});
describe('Approximate match', () => {
@@ -118,7 +239,7 @@ describe('Test vlookup', () => {
NumberValueObject.create(2),
NumberValueObject.create(1)
) as BaseValueObject;
- expect(resultObject.getValue().toString()).toBe('Second');
+ expect(getObjectValue(resultObject)).toStrictEqual([['Second']]);
});
it('Approximate search eight', async () => {
@@ -127,7 +248,7 @@ describe('Test vlookup', () => {
arrayValueObject1.clone(),
NumberValueObject.create(2)
) as BaseValueObject;
- expect(resultObject.getValue().toString()).toBe('Eighth');
+ expect(getObjectValue(resultObject)).toStrictEqual([['Eighth']]);
});
it('Approximate exceeding columns', async () => {
@@ -136,7 +257,7 @@ describe('Test vlookup', () => {
arrayValueObject1.clone(),
NumberValueObject.create(3)
) as BaseValueObject;
- expect(resultObject.getValue().toString()).toBe(ErrorType.VALUE);
+ expect(getObjectValue(resultObject)).toStrictEqual([[ErrorType.REF]]);
});
it('Approximate not match', async () => {
@@ -146,7 +267,7 @@ describe('Test vlookup', () => {
NumberValueObject.create(2),
NumberValueObject.create(1)
) as BaseValueObject;
- expect(resultObject.getValue().toString()).toBe('First');
+ expect(getObjectValue(resultObject)).toStrictEqual([['First']]);
});
it('Approximate not order data', async () => {
@@ -156,7 +277,7 @@ describe('Test vlookup', () => {
NumberValueObject.create(2),
NumberValueObject.create(1)
) as BaseValueObject;
- expect(resultObject.getValue().toString()).toBe(ErrorType.NA);
+ expect(getObjectValue(resultObject)).toStrictEqual([[ErrorType.NA]]);
});
it('Approximate not order data match', async () => {
@@ -165,7 +286,7 @@ describe('Test vlookup', () => {
arrayValueObject2.clone(),
NumberValueObject.create(2)
) as BaseValueObject;
- expect(resultObject.getValue().toString()).toBe('Third');
+ expect(getObjectValue(resultObject)).toStrictEqual([['Third']]);
});
});
});
diff --git a/packages/engine-formula/src/functions/lookup/vlookup/index.ts b/packages/engine-formula/src/functions/lookup/vlookup/index.ts
index 5624cb0b8f..2e6951469b 100644
--- a/packages/engine-formula/src/functions/lookup/vlookup/index.ts
+++ b/packages/engine-formula/src/functions/lookup/vlookup/index.ts
@@ -14,11 +14,15 @@
* limitations under the License.
*/
+import type { Nullable } from '@univerjs/core';
import { ErrorType } from '../../../basics/error-type';
+import { createNewArray, expandArrayValueObject } from '../../../engine/utils/array-object';
import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
+import { BooleanValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
+import { isSingleValueObject } from '../../../engine/utils/value-object';
export class Vlookup extends BaseFunction {
override calculate(
@@ -51,12 +55,91 @@ export class Vlookup extends BaseFunction {
return ErrorValueObject.create(ErrorType.NA);
}
- const rangeLookupValue = this.getZeroOrOneByOneDefault(rangeLookup);
+ rangeLookup = rangeLookup ?? BooleanValueObject.create(true);
- if (rangeLookupValue == null) {
- return ErrorValueObject.create(ErrorType.VALUE);
+ // When neither lookupValue nor rangeLookup is an array, but colIndexNum is an array, expansion is allowed based on the value of colIndexNum. However, if an error is encountered in subsequent matching, the first error needs to be returned (not the entire array)
+ // Otherwise colIndexNum takes the first value
+
+ if (isSingleValueObject(lookupValue) && isSingleValueObject(rangeLookup) && colIndexNum.isArray()) {
+ lookupValue = lookupValue.isArray() ? (lookupValue as ArrayValueObject).getFirstCell() : lookupValue;
+
+ const rangeLookupValue = this.getZeroOrOneByOneDefault(rangeLookup);
+
+ if (rangeLookupValue == null) {
+ return ErrorValueObject.create(ErrorType.VALUE);
+ }
+
+ let errorValue: BaseValueObject | undefined;
+ const result: BaseValueObject[][] = [];
+
+ (colIndexNum as ArrayValueObject).iterator((colIndexNumValueObject: Nullable<BaseValueObject>, rowIndex: number, columnIndex: number) => {
+ if (colIndexNumValueObject === null || colIndexNumValueObject === undefined) {
+ errorValue = ErrorValueObject.create(ErrorType.VALUE);
+ return false;
+ }
+
+ const searchObject = this._handleTableArray(lookupValue, tableArray, colIndexNumValueObject, rangeLookupValue);
+
+ if (searchObject.isError()) {
+ errorValue = searchObject;
+ return false;
+ }
+
+ if (result[rowIndex] === undefined) {
+ result[rowIndex] = [];
+ }
+
+ result[rowIndex][columnIndex] = searchObject;
+ });
+
+ if (errorValue) {
+ return errorValue;
+ }
+
+ return createNewArray(result, result.length, result[0].length, this.unitId || '', this.subUnitId || '');
}
+ // max row length
+ const maxRowLength = Math.max(
+ lookupValue.isArray() ? (lookupValue as ArrayValueObject).getRowCount() : 1,
+ rangeLookup.isArray() ? (rangeLookup as ArrayValueObject).getRowCount() : 1
+ );
+
+ // max column length
+ const maxColumnLength = Math.max(
+ lookupValue.isArray() ? (lookupValue as ArrayValueObject).getColumnCount() : 1,
+ rangeLookup.isArray() ? (rangeLookup as ArrayValueObject).getColumnCount() : 1
+ );
+
+ const lookupValueArray = expandArrayValueObject(maxRowLength, maxColumnLength, lookupValue);
+ const rangeLookupArray = expandArrayValueObject(maxRowLength, maxColumnLength, rangeLookup);
+
+ return lookupValueArray.map((lookupValue, rowIndex, columnIndex) => {
+ if (lookupValue.isError()) {
+ return lookupValue;
+ }
+
+ const rangeLookupValueObject = rangeLookupArray.get(rowIndex, columnIndex);
+
+ if (rangeLookupValueObject == null) {
+ return ErrorValueObject.create(ErrorType.VALUE);
+ }
+
+ if (rangeLookupValueObject.isError()) {
+ return rangeLookupValueObject;
+ }
+
+ const rangeLookupValue = this.getZeroOrOneByOneDefault(rangeLookupValueObject);
+
+ if (rangeLookupValue == null) {
+ return ErrorValueObject.create(ErrorType.VALUE);
+ }
+
+ return this._handleTableArray(lookupValue, tableArray, colIndexNum, rangeLookupValue);
+ });
+ }
+
+ private _handleTableArray(lookupValue: BaseValueObject, tableArray: BaseValueObject, colIndexNum: BaseValueObject, rangeLookupValue: number) {
const colIndexNumValue = this.getIndexNumValue(colIndexNum);
if (colIndexNumValue instanceof ErrorValueObject) {
@@ -65,14 +148,16 @@ export class Vlookup extends BaseFunction {
const searchArray = (tableArray as ArrayValueObject).slice(undefined, [0, 1]);
- const resultArray = (tableArray as ArrayValueObject).slice(undefined, [colIndexNumValue - 1, colIndexNumValue]);
-
- if (searchArray == null || resultArray == null) {
+ if (searchArray == null) {
return ErrorValueObject.create(ErrorType.VALUE);
}
- if (lookupValue.isArray()) {
- return lookupValue.map((value) => this._handleSingleObject(value, searchArray, resultArray, rangeLookupValue));
+ const resultArray = (tableArray as ArrayValueObject).slice(undefined, [colIndexNumValue - 1, colIndexNumValue]);
+
+ // The error reporting priority of lookupValue in Excel is higher than colIndexNum. It is required to execute the query from the first column first, and then take the value of colIndexNum column from the query result.
+ // Here we will first throw the colIndexNum error to avoid unnecessary queries and improve performance.
+ if (resultArray == null) {
+ return ErrorValueObject.create(ErrorType.REF);
}
return this._handleSingleObject(lookupValue, searchArray, resultArray, rangeLookupValue);
diff --git a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx
index a3c1c7087c..f92220abae 100644
--- a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx
+++ b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx
@@ -21,7 +21,6 @@ import {
InsertSheetMutation,
RemoveSheetMutation,
SetTabColorMutation,
- SetWorksheetActivateCommand,
SetWorksheetActiveOperation,
SetWorksheetHideMutation,
SetWorksheetNameCommand,
@@ -108,8 +107,9 @@ export function SheetBarTabs() {
commandService.executeCommand(SetWorksheetOrderCommand.id, { order });
},
onChangeTab: (event: MouseEvent, subUnitId: string) => {
+ // Do not use SetWorksheetActivateCommand, otherwise the sheet will not be switched before the menu pops up, resulting in incorrect menu position.
commandService
- .executeCommand(SetWorksheetActivateCommand.id, {
+ .executeCommand(SetWorksheetActiveOperation.id, {
subUnitId,
unitId: workbook.getUnitId(),
})