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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(formula): vlookup function (#929)
Univerfe73e3bf7995
diff --git a/.vscode/extensions.json b/.vscode/extensions.jsonindex a0b02c08ec..8bc6ff24c6 100644--- a/.vscode/extensions.json+++ b/.vscode/extensions.json@@ -8,6 +8,7 @@"streetsidesoftware.code-spell-checker","tldraw-org.tldraw-vscode","kingwl.vscode-vitest-runner",- "usernamehw.errorlens"+ "usernamehw.errorlens",+ "hoodiecollin.es6-string-typescript"]}diff --git a/packages/engine-formula/src/basics/inverted-index-cache.ts b/packages/engine-formula/src/basics/inverted-index-cache.tsindex 4a1675632e..3af4b79228 100644--- a/packages/engine-formula/src/basics/inverted-index-cache.ts+++ b/packages/engine-formula/src/basics/inverted-index-cache.ts@@ -27,12 +27,12 @@ export class InvertedIndexCache {* }* }*/- private _cache: Map<string, Map<string, Map<number, Map<string | number | boolean, number[]>>>> = new Map();+ private _cache: Map<string, Map<string, Map<number, Map<string | number | boolean | null, number[]>>>> = new Map();private _continueBuildingCache: Map<string, Map<string, Map<number, { startRow: number; endRow: number }>>> =new Map();- set(unitId: string, sheetId: string, column: number, value: string | number | boolean, row: number) {+ set(unitId: string, sheetId: string, column: number, value: string | number | boolean | null, row: number) {if (!this.shouldContinueBuildingCache(unitId, sheetId, column, row)) {return;}@@ -133,6 +133,9 @@ export class InvertedIndexCache {}canUseCache(unitId: string, sheetId: string, column: number, rangeStartRow: number, rangeEndRow: number) {+ if (column === -1 || rangeStartRow === -1 || rangeEndRow === -1) {+ return false;+ }const rowRange = this._continueBuildingCache.get(unitId)?.get(sheetId)?.get(column);if (rowRange == null) {return false;diff --git a/packages/engine-formula/src/engine/ast-node/lambda-node.ts b/packages/engine-formula/src/engine/ast-node/lambda-node.tsindex 22b9e61b5f..965a2fc5c0 100644--- a/packages/engine-formula/src/engine/ast-node/lambda-node.ts+++ b/packages/engine-formula/src/engine/ast-node/lambda-node.ts@@ -18,7 +18,6 @@ import type { Nullable } from '@univerjs/core';import { Tools } from '@univerjs/core';import { Inject } from '@wendellhu/redi';-import { AstNodePromiseType } from '../../basics/common';import { ErrorType } from '../../basics/error-type';import {DEFAULT_TOKEN_LAMBDA_FUNCTION_NAME,@@ -78,17 +77,17 @@ export class LambdaNode extends BaseAstNode {}}- override async executeAsync() {- if (this.isEmptyParamFunction()) {- await this.setValue(new LambdaValueObjectObject(this, this._interpreter, this._lambdaPrivacyVarKeys));- } else {- const children = this.getChildren();- const childrenCount = children.length;- await this.setValue(children[childrenCount - 1].getValue());- }-- return Promise.resolve(AstNodePromiseType.SUCCESS);- }+ // override async executeAsync() {+ // if (this.isEmptyParamFunction()) {+ // await this.setValue(new LambdaValueObjectObject(this, this._interpreter, this._lambdaPrivacyVarKeys));+ // } else {+ // const children = this.getChildren();+ // const childrenCount = children.length;+ // await this.setValue(children[childrenCount - 1].getValue());+ // }++ // return Promise.resolve(AstNodePromiseType.SUCCESS);+ // }}export class LambdaNodeFactory extends BaseAstNodeFactory {diff --git a/packages/engine-formula/src/engine/ast-node/lambda-parameter-node.ts b/packages/engine-formula/src/engine/ast-node/lambda-parameter-node.tsindex 7a81ba474e..e867348629 100644--- a/packages/engine-formula/src/engine/ast-node/lambda-parameter-node.ts+++ b/packages/engine-formula/src/engine/ast-node/lambda-parameter-node.ts@@ -25,6 +25,25 @@ import { BaseAstNode, ErrorNode } from './base-ast-node';import { BaseAstNodeFactory, DEFAULT_AST_NODE_FACTORY_Z_INDEX } from './base-ast-node-factory';import { NODE_ORDER_MAP, NodeType } from './node-type';+function getRootLexerNode(node: Nullable<BaseAstNode>): Nullable<BaseAstNode> {+ if (!node) {+ return;+ }+ if (node.getToken() !== DEFAULT_TOKEN_TYPE_LAMBDA_RUNTIME_PARAMETER) {+ return node;+ }++ const parameterNode = node as LambdaParameterNode;+ const currentLambdaPrivacyVar = parameterNode.getCurrentLambdaPrivacyVar();+ const lambdaParameter = parameterNode.getLambdaParameter();++ if (!currentLambdaPrivacyVar) {+ return;+ }++ return getRootLexerNode(currentLambdaPrivacyVar.get(lambdaParameter));+}+export class LambdaParameterNode extends BaseAstNode {constructor(token: string,@@ -50,7 +69,7 @@ export class LambdaParameterNode extends BaseAstNode {/*** In the case of =lambda(x,y,lambda(a,b,a*b)(x,y))(1,2)*/- const node = this._getRootLexerNode(this._currentLambdaPrivacyVar.get(this._lambdaParameter));+ const node = getRootLexerNode(this._currentLambdaPrivacyVar.get(this._lambdaParameter));if (!node) {const value = this.getValue();if (value == null || value.isError()) {@@ -60,25 +79,6 @@ export class LambdaParameterNode extends BaseAstNode {this.setValue(node.getValue());}}-- private _getRootLexerNode(node: Nullable<BaseAstNode>): Nullable<BaseAstNode> {- if (!node) {- return;- }- if (node.getToken() !== DEFAULT_TOKEN_TYPE_LAMBDA_RUNTIME_PARAMETER) {- return node;- }-- const parameterNode = node as LambdaParameterNode;- const currentLambdaPrivacyVar = parameterNode.getCurrentLambdaPrivacyVar();- const lambdaParameter = parameterNode.getLambdaParameter();-- if (!currentLambdaPrivacyVar) {- return;- }-- return this._getRootLexerNode(currentLambdaPrivacyVar.get(lambdaParameter));- }}export class LambdaParameterNodeFactory extends BaseAstNodeFactory {diff --git a/packages/engine-formula/src/engine/interpreter/interpreter.ts b/packages/engine-formula/src/engine/interpreter/interpreter.tsindex 816f3a1bbd..80b84cfdc3 100644--- a/packages/engine-formula/src/engine/interpreter/interpreter.ts+++ b/packages/engine-formula/src/engine/interpreter/interpreter.ts@@ -119,7 +119,7 @@ export class Interpreter extends Disposable {token.toUpperCase() === DEFAULT_TOKEN_LAMBDA_FUNCTION_NAME &&(item as LambdaNode).isEmptyParamFunction()) {- await item.executeAsync();+ item.execute();continue;}await this._executeAsync(item);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.tsindex cd085d2fa2..db8eecaaf7 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@@ -428,7 +428,7 @@ export class BaseReferenceObject extends ObjectClassType {return this.getCellValueObject(cell);}- toArrayValueObject(): ArrayValueObject {+ toArrayValueObject(useCache: boolean = true): ArrayValueObject {const { startRow, endRow, startColumn, endColumn } = this.getRangePosition();const key = `${this.getUnitId()}_${this.getSheetId()}_${startRow + this._refOffsetY}_${@@ -437,7 +437,7 @@ export class BaseReferenceObject extends ObjectClassType {const array = FORMULA_REF_TO_ARRAY_CACHE.get(key);- if (array) {+ if (array && useCache) {return array;}@@ -470,7 +470,7 @@ export class BaseReferenceObject extends ObjectClassType {const arrayValueObject = new ArrayValueObject(arrayValueObjectData);- FORMULA_REF_TO_ARRAY_CACHE.set(key, arrayValueObject);+ useCache && FORMULA_REF_TO_ARRAY_CACHE.set(key, arrayValueObject);return arrayValueObject;}diff --git a/packages/engine-formula/src/engine/utils/compare.ts b/packages/engine-formula/src/engine/utils/compare.tsindex 8a1b8b2252..d3f1140b67 100644--- a/packages/engine-formula/src/engine/utils/compare.ts+++ b/packages/engine-formula/src/engine/utils/compare.ts@@ -16,6 +16,11 @@import { compareToken } from '../../basics/token';+export enum ArrayBinarySearchType {+ MIN,+ MAX,+}+export function getCompare() {return new Intl.Collator(undefined, { numeric: true }).compare;}diff --git a/packages/engine-formula/src/engine/value-object/__tests__/array-value-object.spec.ts b/packages/engine-formula/src/engine/value-object/__tests__/array-value-object.spec.tsindex 63ba5c444a..f97168b45e 100644--- a/packages/engine-formula/src/engine/value-object/__tests__/array-value-object.spec.ts+++ b/packages/engine-formula/src/engine/value-object/__tests__/array-value-object.spec.ts@@ -37,7 +37,7 @@ describe('arrayValueObject test', () => {describe('slice', () => {it('row==null;column=2,,', () => {- expect(originArrayValueObject.slice(null, [2]).toValue()).toStrictEqual([+ expect(originArrayValueObject.slice(null, [2])?.toValue()).toStrictEqual([[3, 4, 5],[8, 9, 10],[13, 14, 15],@@ -45,29 +45,47 @@ describe('arrayValueObject test', () => {});it('row==2,,;column=2,,', () => {- expect(originArrayValueObject.slice([2], [2]).toValue()).toStrictEqual([[13, 14, 15]]);+ expect(originArrayValueObject.slice([2], [2])?.toValue()).toStrictEqual([[13, 14, 15]]);});it('row==,,2;column=2,,', () => {- expect(originArrayValueObject.slice([undefined, undefined, 2], [2]).toValue()).toStrictEqual([+ expect(originArrayValueObject.slice([undefined, undefined, 2], [2])?.toValue()).toStrictEqual([[3, 4, 5],[13, 14, 15],]);});it('row==1,,;column=null', () => {- expect(originArrayValueObject.slice([1]).toValue()).toStrictEqual([+ expect(originArrayValueObject.slice([1])?.toValue()).toStrictEqual([[6, 7, 8, 9, 10],[11, 12, 13, 14, 15],]);});it('row==0,1,;column=,,2', () => {- expect(originArrayValueObject.slice([0, 1], [undefined, undefined, 2]).toValue()).toStrictEqual([+ expect(originArrayValueObject.slice([0, 1], [undefined, undefined, 2])?.toValue()).toStrictEqual([[1, 3, 5],- [6, 8, 10],]);});++ it('row==0,1,;column=,,2', () => {+ expect(originArrayValueObject.slice(undefined, [2, 3])?.toValue()).toStrictEqual([[3], [8], [13]]);+ });++ it('row==1,3,;column=1,4,', () => {+ expect(originArrayValueObject.slice([1, 3], [1, 4])?.toValue()).toStrictEqual([+ [7, 8, 9],+ [12, 13, 14],+ ]);+ });++ it('row==3,,;column=,,', () => {+ expect(originArrayValueObject.slice([3])?.toValue()).toBeUndefined();+ });++ it('row==,,;column=5,,', () => {+ expect(originArrayValueObject.slice(undefined, [5])?.toValue()).toBeUndefined();+ });});describe('pick', () => {@@ -268,6 +286,16 @@ describe('arrayValueObject test', () => {arrayValueObject = ValueObjectFactory.create('{1,2,3;4,5,6}');expect((arrayValueObject as ArrayValueObject).isArray()).toBeTruthy();++ arrayValueObject = ValueObjectFactory.create(`{+ 1 , 2;+ 4 , 5+ }`);++ expect((arrayValueObject as ArrayValueObject).toValue()).toStrictEqual([+ [1, 2],+ [4, 5],+ ]);});it('ValueObjectFactory create StringValueObject ', () => {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.tsindex 0dc99f3da6..d854a2671c 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@@ -21,10 +21,10 @@ import { ErrorType } from '../../basics/error-type';import { CELL_INVERTED_INDEX_CACHE } from '../../basics/inverted-index-cache';import { $ARRAY_VALUE_REGEX } from '../../basics/regex';import { compareToken } from '../../basics/token';-import { getCompare } from '../utils/compare';+import { ArrayBinarySearchType, getCompare } from '../utils/compare';import type { callbackMapFnType, callbackProductFnType, IArrayValueObject } from './base-value-object';import { BaseValueObject, ErrorValueObject } from './base-value-object';-import { BooleanValueObject, NumberValueObject, StringValueObject } from './primitive-object';+import { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from './primitive-object';enum BatchOperatorType {MINUS,@@ -99,7 +99,7 @@ export function transformToValue(array: BaseValueObject[][] = []) {}export class ArrayValueObject extends BaseValueObject {- private _value: BaseValueObject[][] = [];+ private _values: BaseValueObject[][] = [];private _rowCount: number = -1;@@ -113,6 +113,10 @@ export class ArrayValueObject extends BaseValueObject {private _currentColumn: number = -1;+ private _sliceCache = new Map<string, ArrayValueObject>();++ private _flattenCache: Nullable<ArrayValueObject>;+constructor(rawValue: string | IArrayValueObject) {if (typeof rawValue === 'string') {super(rawValue as string);@@ -121,17 +125,19 @@ export class ArrayValueObject extends BaseValueObject {super(rawString);}- this._value = this._formatValue(rawValue);+ this._values = this._formatValue(rawValue);}override dispose(): void {- this._value.forEach((cells) => {+ this._values.forEach((cells) => {cells.forEach((cell) => {cell.dispose();});});- this._value = [];+ this._values = [];++ this._clearCache();}getRowCount() {@@ -180,11 +186,12 @@ export class ArrayValueObject extends BaseValueObject {}override getArrayValue() {- return this._value;+ return this._values;}override setArrayValue(value: BaseValueObject[][]) {- this._value = value;+ this._clearCache();+ this._values = value;}override isArray() {@@ -192,14 +199,21 @@ export class ArrayValueObject extends BaseValueObject {}get(row: number, column: number) {- return this._value[row][column];+ const v = this._values[row][column];+ if (v == null) {+ return new NullValueObject(0);+ }+ return v;}set(row: number, column: number, value: BaseValueObject) {if (row >= this._rowCount || column >= this._columnCount) {throw new Error('Exceeding array bounds.');}- this._value[row][column] = value;++ this._clearCache();++ this._values[row][column] = value;}getRangePosition() {@@ -234,8 +248,7 @@ export class ArrayValueObject extends BaseValueObject {getFirstCell() {const { startRow, startColumn } = this.getRangePosition();- const valueList = this.getArrayValue();- return valueList[startRow][startColumn];+ return this.get(startRow, startColumn);}/**@@ -249,8 +262,8 @@ export class ArrayValueObject extends BaseValueObject {const takeArrayRowCount = takeArray.getRowCount();const takeArrayColumnCount = takeArray.getColumnCount();- if (takeArrayRowCount !== this._rowCount || takeArrayRowCount !== this._rowCount) {- return this._createNewArray([[new NumberValueObject(0)]], 1, 1);+ if (takeArrayRowCount !== this._rowCount || takeArrayColumnCount !== this._columnCount) {+ return this._createNewArray([[new NullValueObject(0)]], 1, 1);}const newValue: BaseValueObject[][] = [];@@ -279,16 +292,25 @@ export class ArrayValueObject extends BaseValueObject {* https://numpy.org/doc/stable/reference/generated/numpy.chararray.flatten.html#numpy.chararray.flatten*/flatten() {+ if (this._flattenCache != null) {+ return this._flattenCache;+ }+const newValue: BaseValueObject[][] = [];newValue[0] = [];for (let r = 0; r < this._rowCount; r++) {- for (let c = 0; c < this._rowCount; c++) {+ for (let c = 0; c < this._columnCount; c++) {const value = this.get(r, c);newValue[0].push(value);}}- return this._createNewArray(newValue, 1, newValue[0].length);++ const arrayV = this._createNewArray(newValue, 1, newValue[0].length);++ this._flattenCache = arrayV;++ return arrayV;}/**@@ -300,44 +322,75 @@ export class ArrayValueObject extends BaseValueObject {*/slice(rowParam: Nullable<Array<Nullable<number>>>, columnParam: Nullable<Array<Nullable<number>>>) {let rowStart = 0;- let rowStop = this._rowCount - 1;+ let rowStop = this._rowCount;let rowStep = 1;let columnStart = 0;- let columnStop = this._columnCount - 1;+ let columnStop = this._columnCount;let columnStep = 1;if (rowParam != null) {rowStart = rowParam[0] || 0;- rowStop = rowParam[1] || this._rowCount - 1;+ rowStop = rowParam[1] || this._rowCount;rowStep = rowParam[2] || 1;}if (columnParam != null) {columnStart = columnParam[0] || 0;- columnStop = columnParam[1] || this._columnCount - 1;+ columnStop = columnParam[1] || this._columnCount;columnStep = columnParam[2] || 1;}+ if (rowStart >= this._rowCount || columnStart >= this._columnCount) {+ return;+ }++ const cacheKey = `${rowStart}_${rowStop}_${rowStep}_${columnStart}_${columnStop}_${columnStep}`;++ const cache = this._sliceCache.get(cacheKey);++ if (cache != null) {+ return cache;+ }+const result: BaseValueObject[][] = [];- const array = this._value;+ const array = this._values;let result_row_index = 0;let result_column_index = 0;- for (let r = rowStart; r <= rowStop; r += rowStep) {+ for (let r = rowStart; r < rowStop; r += rowStep) {result_column_index = 0;if (result[result_row_index] == null) {result[result_row_index] = [];}- for (let c = columnStart; c <= columnStop; c += columnStep) {+ for (let c = columnStart; c < columnStop; c += columnStep) {result[result_row_index][result_column_index] = array[r][c];result_column_index++;}result_row_index++;}- return this._createNewArray(result, result.length, result[0].length);+ if (result.length === 0 || result[0].length === 0) {+ return;+ }++ /**+ * When iterating, arrayValue will create an inverted index cache for cell reference data.+ * If the array is created by ref, it will hit the cache,+ * but arrays derived from another array will lose the caching ability.+ * Here, based on the slice range, it is determined whether to set row and column to -1;+ * -1 means that caching is not enabled.+ */+ const startRow = rowStep > 1 ? -1 : rowStart + this._currentRow;++ const startColumn = columnStep > 1 ? -1 : columnStart + this._currentColumn;++ const newResultArray = this._createNewArray(result, result.length, result[0].length, startRow, startColumn);++ this._sliceCache.set(cacheKey, newResultArray);++ return newResultArray;}sum() {@@ -468,19 +521,22 @@ export class ArrayValueObject extends BaseValueObject {sortByRow(index: number) {// new Intl.Collator('zh', { numeric: true }).compare;- const result: BaseValueObject[][] = this._transposeArray(this._value);+ const result: BaseValueObject[][] = this._transposeArray(this._values);result.sort(this._sort(index));- this._value = this._transposeArray(result);+ this._clearCache();++ this._values = this._transposeArray(result);}sortByColumn(index: number) {- this._value.sort(this._sort(index));+ this._clearCache();+ this._values.sort(this._sort(index));}transpose() {- const transposeArray = this._transposeArray(this._value);+ const transposeArray = this._transposeArray(this._values);const rowCount = this._rowCount;const columnCount = this._columnCount;@@ -488,6 +544,57 @@ export class ArrayValueObject extends BaseValueObject {return this._createNewArray(transposeArray, columnCount, rowCount);}+ binarySearch(valueObject: BaseValueObject, searchType: ArrayBinarySearchType = ArrayBinarySearchType.MIN) {+ if (valueObject.isError()) {+ return;+ }++ const flattenArrayValue = this.flatten();+ const valueMatrix = flattenArrayValue.getArrayValue();+ const valueArray = valueMatrix[0];++ const compareFunc = getCompare();++ const value = valueObject.getValue().toString();++ let start = 0;+ let end = valueArray.length - 1;++ let lastValue = null;++ while (start <= end) {+ const middle = Math.floor((start + end) / 2);+ const compareTo = valueArray[middle];++ const compareToValue = compareTo.getValue();++ const compare = compareFunc(compareToValue.toString(), value);++ if (compare === 0) {+ // Found the value, return the value from the returnColumn+ return middle;+ }++ if (compare === -1) {+ start = middle + 1;++ if (searchType === ArrayBinarySearchType.MIN) {+ lastValue = middle;+ }+ } else {+ // compareTo > value+ end = middle - 1;++ if (searchType === ArrayBinarySearchType.MAX) {+ lastValue = middle;+ }+ }+ }++ // Value not found+ return lastValue;+ }+override getNegative(): BaseValueObject {const arrayValueObject = new ArrayValueObject('{0}');return arrayValueObject.minus(this);@@ -546,7 +653,7 @@ export class ArrayValueObject extends BaseValueObject {for (let r = 0; r < rowCount; r++) {const rowList: BaseValueObject[] = [];for (let c = 0; c < columnCount; c++) {- const currentValue = this._value?.[r]?.[c];+ const currentValue = this._values?.[r]?.[c];if (currentValue) {if (currentValue.isError()) {@@ -857,7 +964,12 @@ export class ArrayValueObject extends BaseValueObject {}toValue() {- return transformToValue(this._value);+ return transformToValue(this._values);+ }++ private _clearCache() {+ this._flattenCache = null;+ this._sliceCache.clear();}private _sort(index: number) {@@ -988,16 +1100,14 @@ export class ArrayValueObject extends BaseValueObject {valueObject.getValue());- if (rowPositions != null) {- for (let r = 0; r < rowCount; r++) {- if (result[r] == null) {- result[r] = [];- }- if (rowPositions.includes(r + startRow)) {- result[r][column] = new BooleanValueObject(true);- } else {- result[r][column] = new BooleanValueObject(false);- }+ for (let r = 0; r < rowCount; r++) {+ if (result[r] == null) {+ result[r] = [];+ }+ if (rowPositions?.includes(r + startRow)) {+ result[r][column] = new BooleanValueObject(true);+ } else {+ result[r][column] = new BooleanValueObject(false);}}} else {@@ -1039,6 +1149,14 @@ export class ArrayValueObject extends BaseValueObject {}}});+ } else {+ for (let r = 0; r < rowCount; r++) {+ if (result[r] == null) {+ result[r] = [];+ }++ result[r][column] = new BooleanValueObject(false);+ }}}@@ -1046,16 +1164,8 @@ export class ArrayValueObject extends BaseValueObject {}}- CELL_INVERTED_INDEX_CACHE.setContinueBuildingCache(- unitId,- sheetId,- column + startColumn,- startRow,- startRow + rowCount - 1- );-for (let r = 0; r < rowCount; r++) {- const currentValue = this._value?.[r]?.[column];+ const currentValue = this._values?.[r]?.[column];if (result[r] == null) {result[r] = [];}@@ -1149,6 +1259,8 @@ export class ArrayValueObject extends BaseValueObject {(currentValue as ErrorValueObject).getErrorType(),r + startRow);+ } else if (currentValue.isNull()) {+ CELL_INVERTED_INDEX_CACHE.set(unitId, sheetId, column + startColumn, null, r + startRow);} else {CELL_INVERTED_INDEX_CACHE.set(unitId,@@ -1159,6 +1271,14 @@ export class ArrayValueObject extends BaseValueObject {);}}++ CELL_INVERTED_INDEX_CACHE.setContinueBuildingCache(+ unitId,+ sheetId,+ column + startColumn,+ startRow,+ startRow + rowCount - 1+ );}private _batchOperatorArray(@@ -1190,13 +1310,13 @@ export class ArrayValueObject extends BaseValueObject {for (let c = 0; c < columnCount; c++) {let currentValue: Nullable<BaseValueObject>;if (currentCalculateType === ArrayCalculateType.SINGLE) {- currentValue = this._value?.[0]?.[0];+ currentValue = this._values?.[0]?.[0];} else if (currentCalculateType === ArrayCalculateType.ROW) {- currentValue = this._value?.[0]?.[c];+ currentValue = this._values?.[0]?.[c];} else if (currentCalculateType === ArrayCalculateType.COLUMN) {- currentValue = this._value?.[r]?.[0];+ currentValue = this._values?.[r]?.[0];} else {- currentValue = this._value?.[r]?.[c];+ currentValue = this._values?.[r]?.[c];}let opValue: Nullable<BaseValueObject>;@@ -1364,15 +1484,26 @@ export class ArrayValueObject extends BaseValueObject {return result;}- private _createNewArray(result: BaseValueObject[][], rowCount: number, columnCount: number) {+ private _createNewArray(+ result: BaseValueObject[][],+ rowCount: number,+ columnCount: number,+ row: number = -1,+ column: number = -1+ ) {+ if (this._currentColumn === -1 || this._currentRow === -1) {+ row = -1;+ column = -1;+ }+const arrayValueObjectData: IArrayValueObject = {calculateValueList: result,rowCount,columnCount,unitId: this.getUnitId(),sheetId: this.getSheetId(),- row: this._currentRow,- column: this._currentColumn,+ row,+ column,};return new ArrayValueObject(arrayValueObjectData);@@ -1392,8 +1523,8 @@ export class ValueObjectFactory {if (isRealNum(rawValue)) {return new NumberValueObject(rawValue);}- if (new RegExp($ARRAY_VALUE_REGEX, 'g').test(rawValue)) {- return new ArrayValueObject(rawValue);+ if (new RegExp($ARRAY_VALUE_REGEX, 'g').test(rawValue.replace(/\n/g, '').replace(/\r/g, ''))) {+ return new ArrayValueObject(rawValue.replace(/\n/g, '').replace(/\r/g, ''));}return new StringValueObject(rawValue);}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.tsindex fd5661211b..af13d31489 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@@ -14,6 +14,7 @@* limitations under the License.*/+/* eslint-disable @typescript-eslint/no-unused-vars */import { ConcatenateType } from '../../basics/common';import { ErrorType } from '../../basics/error-type';import { ObjectClassType } from '../../basics/object-class-type';@@ -400,11 +401,18 @@ export class ErrorValueObject extends BaseValueObject {super(_errorType);}+ /**+ * @deprecated use 'new' to replace.+ */static create(errorType: ErrorType, errorContent?: string) {const errorValueObject = new ErrorValueObject(errorType, errorContent);return errorValueObject;}+ override getValue() {+ return this._errorType;+ }+getErrorType() {return this._errorType;}diff --git a/packages/engine-formula/src/engine/value-object/lambda-value-object.ts b/packages/engine-formula/src/engine/value-object/lambda-value-object.tsindex aac5fc3e69..82900d0fe6 100644--- a/packages/engine-formula/src/engine/value-object/lambda-value-object.ts+++ b/packages/engine-formula/src/engine/value-object/lambda-value-object.ts@@ -14,6 +14,8 @@* limitations under the License.*/+import type { Nullable } from '@univerjs/core';+import { ErrorType } from '../../basics/error-type';import { DEFAULT_TOKEN_TYPE_LAMBDA_RUNTIME_PARAMETER } from '../../basics/token-type';import type { BaseAstNode } from '../ast-node/base-ast-node';@@ -23,6 +25,31 @@ import type { BaseReferenceObject } from '../reference-object/base-reference-objimport { AsyncObject } from '../reference-object/base-reference-object';import { BaseValueObject, ErrorValueObject } from './base-value-object';+function getRootLexerHasValueNode(node: Nullable<BaseAstNode>): Nullable<BaseAstNode> {+ if (!node) {+ return;+ }+ if (node.getToken() !== DEFAULT_TOKEN_TYPE_LAMBDA_RUNTIME_PARAMETER) {+ return node;+ }++ const parameterNode = node as LambdaParameterNode;+ const currentLambdaPrivacyVar = parameterNode.getCurrentLambdaPrivacyVar();+ const lambdaParameter = parameterNode.getLambdaParameter();++ if (!currentLambdaPrivacyVar) {+ return;+ }++ const chainNode = currentLambdaPrivacyVar.get(lambdaParameter);++ if (chainNode == null && node.getValue()) {+ return node;+ }++ return getRootLexerHasValueNode(chainNode);+}+export class LambdaValueObjectObject extends BaseValueObject {private _lambdaPrivacyValueMap = new Map<string, BaseValueObject>();@@ -82,6 +109,12 @@ export class LambdaValueObjectObject extends BaseValueObject {const value = this._lambdaPrivacyValueMap.get(lambdaParameter);if (value) {(item as LambdaParameterNode).setValue(value);+ } else {+ const currentLambdaPrivacyVar = (item as LambdaParameterNode).getCurrentLambdaPrivacyVar();+ const node = getRootLexerHasValueNode(currentLambdaPrivacyVar.get(lambdaParameter));+ if (node != null) {+ (item as LambdaParameterNode).setValue(node.getValue());+ }}continue;}diff --git a/packages/engine-formula/src/functions/__tests__/create-command-test-bed.ts b/packages/engine-formula/src/functions/__tests__/create-command-test-bed.tsindex ac5aa69e19..9e299c3574 100644--- a/packages/engine-formula/src/functions/__tests__/create-command-test-bed.ts+++ b/packages/engine-formula/src/functions/__tests__/create-command-test-bed.ts@@ -30,6 +30,7 @@ import { Inject, Injector } from '@wendellhu/redi';import type { ISheetData } from '../../basics/common';import { Lexer } from '../../engine/analysis/lexer';+import { LexerTreeBuilder } from '../../engine/analysis/lexer-tree-builder';import { AstTreeBuilder } from '../../engine/analysis/parser';import { AstRootNodeFactory } from '../../engine/ast-node/ast-root-node';import { FunctionNodeFactory } from '../../engine/ast-node/function-node';@@ -46,9 +47,11 @@ import { Interpreter } from '../../engine/interpreter/interpreter';import type { FormulaDataModel } from '../../models/formula-data.model';import { CalculateFormulaService } from '../../services/calculate-formula.service';import { FormulaCurrentConfigService, IFormulaCurrentConfigService } from '../../services/current-data.service';+import { DefinedNamesService, IDefinedNamesService } from '../../services/defined-names.service';import { FunctionService, IFunctionService } from '../../services/function.service';import { IOtherFormulaManagerService, OtherFormulaManagerService } from '../../services/other-formula-manager.service';import { FormulaRuntimeService, IFormulaRuntimeService } from '../../services/runtime.service';+import { ISuperTableService, SuperTableService } from '../../services/super-table.service';const TEST_WORKBOOK_DATA: IWorkbookData = {id: 'test',@@ -96,11 +99,14 @@ export function createCommandTestBed(workbookConfig?: IWorkbookData, dependencieoverride onStarting(injector: Injector): void {injector.add([CalculateFormulaService]);injector.add([Lexer]);+ injector.add([LexerTreeBuilder]);injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);injector.add([IFunctionService, { useClass: FunctionService }]);injector.add([IOtherFormulaManagerService, { useClass: OtherFormulaManagerService }]);+ injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);+ injector.add([ISuperTableService, { useClass: SuperTableService }]);injector.add([FormulaDependencyGenerator]);injector.add([Interpreter]);diff --git a/packages/engine-formula/src/functions/array/function-map.ts b/packages/engine-formula/src/functions/array/function-map.tsindex 28cf15d59b..86e577d447 100644--- a/packages/engine-formula/src/functions/array/function-map.ts+++ b/packages/engine-formula/src/functions/array/function-map.ts@@ -14,7 +14,4 @@* limitations under the License.*/-import { FUNCTION_NAMES_ARRAY } from './function-names';-import { Makearray } from './makearray';--export const functionArray = [[Makearray, FUNCTION_NAMES_ARRAY.MAKEARRAY]];+export const functionArray = [];diff --git a/packages/engine-formula/src/functions/array/function-names.ts b/packages/engine-formula/src/functions/array/function-names.tsindex b2fea38faa..ddb8a624f8 100644--- a/packages/engine-formula/src/functions/array/function-names.ts+++ b/packages/engine-formula/src/functions/array/function-names.ts@@ -14,6 +14,4 @@* limitations under the License.*/-export enum FUNCTION_NAMES_ARRAY {- MAKEARRAY = 'MAKEARRAY',-}+export enum FUNCTION_NAMES_ARRAY {}diff --git a/packages/engine-formula/src/functions/base-function.ts b/packages/engine-formula/src/functions/base-function.tsindex fd7344e2b8..19cea3e2c6 100644--- a/packages/engine-formula/src/functions/base-function.ts+++ b/packages/engine-formula/src/functions/base-function.ts@@ -16,9 +16,10 @@import { Disposable } from '@univerjs/core';-import type { IFunctionNames } from '..';import { ErrorType } from '../basics/error-type';+import type { IFunctionNames } from '../basics/function';import type { FunctionVariantType, NodeValueType } from '../engine/reference-object/base-reference-object';+import type { ArrayValueObject } from '../engine/value-object/array-value-object';import { type BaseValueObject, ErrorValueObject } from '../engine/value-object/base-value-object';export class BaseFunction extends Disposable {@@ -45,4 +46,30 @@ export class BaseFunction extends Disposable {checkArrayType(variant: FunctionVariantType) {return variant.isReferenceObject() || (variant.isValueObject() && (variant as BaseValueObject).isArray());}++ getIndexNumValue(indexNum: BaseValueObject) {+ if (indexNum.isArray()) {+ indexNum = (indexNum as ArrayValueObject).getFirstCell();+ }++ if (indexNum.isBoolean()) {+ const colIndexNumV = indexNum.getValue() as boolean;+ if (colIndexNumV === false) {+ return new ErrorValueObject(ErrorType.VALUE);+ }++ return 1;+ }+ if (indexNum.isString()) {+ const colIndexNumV = Number(indexNum.getValue() as string);+ if (isNaN(colIndexNumV)) {+ return new ErrorValueObject(ErrorType.REF);+ }+ } else if (indexNum.isNumber()) {+ const colIndexNumV = indexNum.getValue() as number;+ return colIndexNumV;+ }++ return new ErrorValueObject(ErrorType.VALUE);+ }}diff --git a/packages/engine-formula/src/functions/logical/function-map.ts b/packages/engine-formula/src/functions/logical/function-map.tsindex b7adc665d5..b4ad601f50 100644--- a/packages/engine-formula/src/functions/logical/function-map.ts+++ b/packages/engine-formula/src/functions/logical/function-map.ts@@ -14,4 +14,11 @@* limitations under the License.*/-export const functionLogical = [];+import { FUNCTION_NAMES_LOGICAL } from './function-names';+import { Lambda } from './lambda';+import { Makearray } from './makearray';++export const functionLogical = [+ [Lambda, FUNCTION_NAMES_LOGICAL.LAMBDA],+ [Makearray, FUNCTION_NAMES_LOGICAL.MAKEARRAY],+];diff --git a/packages/engine-formula/src/functions/logical/lambda/index.ts b/packages/engine-formula/src/functions/logical/lambda/index.tsnew file mode 100644index 0000000000..725728fb24--- /dev/null+++ b/packages/engine-formula/src/functions/logical/lambda/index.ts@@ -0,0 +1,29 @@+/**+ * 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 { ErrorType } from '../../../basics/error-type';+import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';+import { BaseFunction } from '../../base-function';++/**+ * Lambda functions are unique and are generated directly by the higher level.+ * Please refer to the lambdaNode; here, it serves the purpose of a placeholder for the formula.+ */+export class Lambda extends BaseFunction {+ override calculate(...variants: BaseValueObject[]) {+ return new ErrorValueObject(ErrorType.VALUE);+ }+}diff --git a/packages/engine-formula/src/functions/logical/makearray/__test__/index.spec.ts b/packages/engine-formula/src/functions/logical/makearray/__test__/index.spec.tsnew file mode 100644index 0000000000..3a8dbd3850--- /dev/null+++ b/packages/engine-formula/src/functions/logical/makearray/__test__/index.spec.ts@@ -0,0 +1,102 @@+/**+ * 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.+ */++/* eslint-disable no-magic-numbers */+import type { Injector } from '@wendellhu/redi';+import { beforeEach, describe, expect, it } from 'vitest';++import type { BaseValueObject } from '../../../..';+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 { ArrayValueObject } from '../../../../engine/value-object/array-value-object';+import { IFunctionService } from '../../../../services/function.service';+import { createCommandTestBed } from '../../../__tests__/create-command-test-bed';+import { FUNCTION_NAMES_META } from '../../../meta/function-names';+import { Multiply } from '../../../meta/multiply';+import { FUNCTION_NAMES_LOGICAL } from '../../function-names';+import { Lambda } from '../../lambda';+import { Makearray } from '..';++describe('Test makearray', () => {+ // const textFunction = new Makearray(FUNCTION_NAMES_LOGICAL.MAKEARRAY);+ let get: Injector['get'];+ let lexer: Lexer;+ let astTreeBuilder: AstTreeBuilder;+ let interpreter: Interpreter;++ beforeEach(() => {+ const testBed = createCommandTestBed();++ get = testBed.get;++ lexer = get(Lexer);+ astTreeBuilder = get(AstTreeBuilder);+ interpreter = get(Interpreter);++ const functionService = get(IFunctionService);++ functionService.registerExecutors(+ new Makearray(FUNCTION_NAMES_LOGICAL.MAKEARRAY),+ new Lambda(FUNCTION_NAMES_LOGICAL.LAMBDA),+ new Multiply(FUNCTION_NAMES_META.MULTIPLY)+ );+ });++ describe('normal', () => {+ it('multiply', async () => {+ const lexerNode = lexer.treeBuilder('=MAKEARRAY(4, 4,LAMBDA(x,y,x*y))');++ const astNode = astTreeBuilder.parse(lexerNode as LexerNode);++ const result = await interpreter.executeAsync(astNode as BaseAstNode);++ expect((result as ArrayValueObject).toValue()).toStrictEqual([+ [1, 2, 3, 4],+ [2, 4, 6, 8],+ [3, 6, 9, 12],+ [4, 8, 12, 16],+ ]);+ });++ it('multiply lambda nest', async () => {+ const lexerNode = lexer.treeBuilder('=LAMBDA(x,y,LAMBDA(a,b,a*b)(x, y))(3,5)');++ const astNode = astTreeBuilder.parse(lexerNode as LexerNode);++ const result = await interpreter.executeAsync(astNode as BaseAstNode);++ expect((result as BaseValueObject).getValue()).toStrictEqual(15);+ });++ it('multiply nest', async () => {+ const lexerNode = lexer.treeBuilder('=MAKEARRAY(4, 4,LAMBDA(x,y,LAMBDA(a,b,LAMBDA(i,j,i*j)(a, b))(x, y)))');++ const astNode = astTreeBuilder.parse(lexerNode as LexerNode);++ const result = await interpreter.executeAsync(astNode as BaseAstNode);++ expect((result as ArrayValueObject).toValue()).toStrictEqual([+ [1, 2, 3, 4],+ [2, 4, 6, 8],+ [3, 6, 9, 12],+ [4, 8, 12, 16],+ ]);+ });+ });+});diff --git a/packages/engine-formula/src/functions/array/makearray/index.ts b/packages/engine-formula/src/functions/logical/makearray/index.tssimilarity index 74%rename from packages/engine-formula/src/functions/array/makearray/index.tsrename to packages/engine-formula/src/functions/logical/makearray/index.tsindex 92f503af03..dc693e4e19 100644--- a/packages/engine-formula/src/functions/array/makearray/index.ts+++ b/packages/engine-formula/src/functions/logical/makearray/index.ts@@ -17,7 +17,6 @@import { ErrorType } from '../../../basics/error-type';import type { AsyncObject } from '../../../engine/reference-object/base-reference-object';import { AsyncArrayObject } from '../../../engine/reference-object/base-reference-object';-import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';import type { LambdaValueObjectObject } from '../../../engine/value-object/lambda-value-object';import { NumberValueObject } from '../../../engine/value-object/primitive-object';@@ -29,27 +28,19 @@ export class Makearray extends BaseFunction {return new ErrorValueObject(ErrorType.VALUE);}- let row = variants[0];+ const row = this.getIndexNumValue(variants[0]);- let column = variants[1];-- if (!(variants[2].isValueObject() && (variants[2] as LambdaValueObjectObject).isLambda())) {- return new ErrorValueObject(ErrorType.VALUE);- }-- if (row.isArray()) {- row = (row as ArrayValueObject).getFirstCell();+ if (typeof row !== 'number') {+ return row;}- if (column.isArray()) {- column = (column as ArrayValueObject).getFirstCell();- }+ const column = this.getIndexNumValue(variants[1]);- if (!row.isNumber()) {- return new ErrorValueObject(ErrorType.VALUE);+ if (typeof column !== 'number') {+ return column;}- if (!column.isNumber()) {+ if (!(variants[2].isValueObject() && (variants[2] as LambdaValueObjectObject).isLambda())) {return new ErrorValueObject(ErrorType.VALUE);}@@ -57,11 +48,11 @@ export class Makearray extends BaseFunction {const result: Array<Array<BaseValueObject | AsyncObject>> = [];- for (let r = 0; r < (row as NumberValueObject).getValue(); r++) {+ for (let r = 0; r < row; r++) {if (result[r] == null) {result[r] = [];}- for (let c = 0; c < (column as NumberValueObject).getValue(); c++) {+ for (let c = 0; c < column; c++) {const value = lambda.execute(new NumberValueObject(r + 1), new NumberValueObject(c + 1));result[r][c] = value;diff --git a/packages/engine-formula/src/functions/lookup/function-map.ts b/packages/engine-formula/src/functions/lookup/function-map.tsindex 33207f511a..e88eb1598b 100644--- a/packages/engine-formula/src/functions/lookup/function-map.ts+++ b/packages/engine-formula/src/functions/lookup/function-map.ts@@ -18,9 +18,11 @@ import { Address } from './address';import { FUNCTION_NAMES_LOOKUP } from './function-names';import { Indirect } from './indirect';import { Offset } from './offset';+import { Vlookup } from './vlookup';export const functionLookup = [[Address, FUNCTION_NAMES_LOOKUP.ADDRESS],[Indirect, FUNCTION_NAMES_LOOKUP.INDIRECT],[Offset, FUNCTION_NAMES_LOOKUP.OFFSET],+ [Vlookup, FUNCTION_NAMES_LOOKUP.VLOOKUP],];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.tsnew file mode 100644index 0000000000..035dcdced5--- /dev/null+++ b/packages/engine-formula/src/functions/lookup/vlookup/__tests__/index.spec.ts@@ -0,0 +1,172 @@+/**+ * 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.+ */++/* eslint-disable no-magic-numbers */+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 { FUNCTION_NAMES_LOOKUP } from '../../function-names';+import { Vlookup } from '..';++const arrayValueObject1 = new ArrayValueObject(/*ts*/ `{+ 1, "First";+ 2, "Second";+ 3, "Third";+ 4, "Fourth";+ 5, "Fifth";+ 6, "Sixth";+ 7, "Seventh";+ 8, "Eighth"+}`);++const arrayValueObject2 = new ArrayValueObject(/*ts*/ `{+ 4, "Fourth";+ 5, "Fifth";+ 6, "Sixth";+ 7, "Seventh";+ 8, "Eighth";+ 1, "First";+ 2, "Second";+ 3, "Third"+}`);++const matchArrayValueObject = new ArrayValueObject(/*ts*/ `{+ 1, 3;+ 4, 6;+ 8, 7+}`);++describe('Test vlookup', () => {+ const textFunction = new Vlookup(FUNCTION_NAMES_LOOKUP.VLOOKUP);++ describe('Exact match', () => {+ it('Search two', async () => {+ const resultObject = textFunction.calculate(+ new NumberValueObject(2),+ arrayValueObject1,+ new NumberValueObject(2),+ new NumberValueObject(0)+ ) as BaseValueObject;+ expect(resultObject.getValue().toString()).toBe('Second');+ });++ it('Search eight', async () => {+ const resultObject = textFunction.calculate(+ new NumberValueObject(8),+ arrayValueObject1,+ new NumberValueObject(2),+ new NumberValueObject(0)+ ) as BaseValueObject;+ expect(resultObject.getValue().toString()).toBe('Eighth');+ });++ it('Exceeding columns', async () => {+ const resultObject = textFunction.calculate(+ new NumberValueObject(8),+ arrayValueObject1,+ new NumberValueObject(3),+ new NumberValueObject(0)+ ) as BaseValueObject;+ expect(resultObject.getValue().toString()).toBe(ErrorType.VALUE);+ });++ it('Not match', async () => {+ const resultObject = textFunction.calculate(+ new NumberValueObject(100),+ arrayValueObject1,+ new NumberValueObject(2),+ new NumberValueObject(0)+ ) as BaseValueObject;+ expect(resultObject.getValue().toString()).toBe(ErrorType.NA);+ });++ it('array', async () => {+ const resultObject = textFunction.calculate(+ matchArrayValueObject,+ arrayValueObject1,+ new NumberValueObject(2),+ new NumberValueObject(0)+ ) as BaseValueObject;+ expect((resultObject as ArrayValueObject).toValue()).toStrictEqual([+ ['First', 'Third'],+ ['Fourth', 'Sixth'],+ ['Eighth', 'Seventh'],+ ]);+ });+ });++ describe('Approximate match', () => {+ it('Approximate search two', async () => {+ const resultObject = textFunction.calculate(+ new NumberValueObject(2),+ arrayValueObject1,+ new NumberValueObject(2),+ new NumberValueObject(1)+ ) as BaseValueObject;+ expect(resultObject.getValue().toString()).toBe('Second');+ });++ it('Approximate search eight', async () => {+ const resultObject = textFunction.calculate(+ new NumberValueObject(8),+ arrayValueObject1,+ new NumberValueObject(2)+ ) as BaseValueObject;+ expect(resultObject.getValue().toString()).toBe('Eighth');+ });++ it('Approximate exceeding columns', async () => {+ const resultObject = textFunction.calculate(+ new NumberValueObject(8),+ arrayValueObject1,+ new NumberValueObject(3)+ ) as BaseValueObject;+ expect(resultObject.getValue().toString()).toBe(ErrorType.VALUE);+ });++ it('Approximate not match', async () => {+ const resultObject = textFunction.calculate(+ new NumberValueObject(100),+ arrayValueObject1,+ new NumberValueObject(2),+ new NumberValueObject(1)+ ) as BaseValueObject;+ expect(resultObject.getValue().toString()).toBe('Eighth');+ });++ it('Approximate not order data', async () => {+ const resultObject = textFunction.calculate(+ new NumberValueObject(2),+ arrayValueObject2,+ new NumberValueObject(2),+ new NumberValueObject(1)+ ) as BaseValueObject;+ expect(resultObject.getValue().toString()).toBe(ErrorType.NA);+ });++ it('Approximate not order data match', async () => {+ const resultObject = textFunction.calculate(+ new NumberValueObject(8),+ arrayValueObject2,+ new NumberValueObject(2)+ ) as BaseValueObject;+ expect(resultObject.getValue().toString()).toBe('Third');+ });+ });+});diff --git a/packages/engine-formula/src/functions/lookup/vlookup/index.ts b/packages/engine-formula/src/functions/lookup/vlookup/index.tsnew file mode 100644index 0000000000..dbd74d592d--- /dev/null+++ b/packages/engine-formula/src/functions/lookup/vlookup/index.ts@@ -0,0 +1,136 @@+/**+ * 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 { ArrayValueObject } from '../../..';+import { ErrorType } from '../../../basics/error-type';+import type { BaseValueObject } from '../../../engine/value-object/base-value-object';+import { ErrorValueObject } from '../../../engine/value-object/base-value-object';+import { BaseFunction } from '../../base-function';++export class Vlookup extends BaseFunction {+ override calculate(+ lookupValue: BaseValueObject,+ tableArray: BaseValueObject,+ colIndexNum: BaseValueObject,+ rangeLookup?: BaseValueObject+ ) {+ if (lookupValue.isError()) {+ return lookupValue;+ }++ if (tableArray.isError()) {+ return new ErrorValueObject(ErrorType.REF);+ }++ if (!tableArray.isArray()) {+ return new ErrorValueObject(ErrorType.VALUE);+ }++ if (colIndexNum.isError()) {+ return new ErrorValueObject(ErrorType.NA);+ }++ if (rangeLookup?.isError()) {+ return new ErrorValueObject(ErrorType.NA);+ }++ const rangeLookupValue = this._getRangeLookupValue(rangeLookup);++ if (rangeLookupValue == null) {+ return new ErrorValueObject(ErrorType.VALUE);+ }++ const colIndexNumValue = this.getIndexNumValue(colIndexNum);++ if (colIndexNumValue instanceof ErrorValueObject) {+ return colIndexNumValue;+ }++ const searchArray = (tableArray as ArrayValueObject).slice(undefined, [0, 1]);++ const resultArray = (tableArray as ArrayValueObject).slice(undefined, [colIndexNumValue - 1, colIndexNumValue]);++ if (searchArray == null || resultArray == null) {+ return new ErrorValueObject(ErrorType.VALUE);+ }++ if (lookupValue.isArray()) {+ return lookupValue.map((value) => {+ return this._handleSingleObject(value, searchArray, resultArray, rangeLookupValue);+ });+ }++ return this._handleSingleObject(lookupValue, searchArray, resultArray, rangeLookupValue);+ }++ private _handleSingleObject(+ value: BaseValueObject,+ searchArray: ArrayValueObject,+ resultArray: ArrayValueObject,+ rangeLookupValue: number+ ) {+ if (rangeLookupValue === 0) {+ const resultValue = resultArray.pick(searchArray.isEqual(value) as ArrayValueObject).getFirstCell();+ if (resultValue.isNull()) {+ return new ErrorValueObject(ErrorType.NA);+ }++ return resultValue;+ }++ const row = searchArray.binarySearch(value);++ if (row == null) {+ return new ErrorValueObject(ErrorType.NA);+ }++ const resultValue = resultArray.get(row, 0);++ if (resultValue.isNull()) {+ return new ErrorValueObject(ErrorType.NA);+ }++ return resultValue;+ }++ private _getRangeLookupValue(rangeLookup?: BaseValueObject) {+ if (rangeLookup == null) {+ return 1;+ }++ let rangeLookupValue = 1;++ if (rangeLookup.isArray()) {+ rangeLookup = (rangeLookup as ArrayValueObject).getFirstCell();+ }++ if (rangeLookup.isBoolean()) {+ const rangeLookupV = rangeLookup.getValue() as boolean;+ if (rangeLookupV === false) {+ rangeLookupValue = 0;+ }+ } else if (rangeLookup.isString()) {+ return;+ } else if (rangeLookup.isNumber()) {+ const rangeLookupV = rangeLookup.getValue() as number;+ if (rangeLookupV === 0) {+ rangeLookupValue = 0;+ }+ }++ return rangeLookupValue;+ }+}diff --git a/packages/sheets-formula/src/locale/function-list/logical/en-US.ts b/packages/sheets-formula/src/locale/function-list/logical/en-US.tsindex 1df32e3ef9..86edb9c614 100644--- a/packages/sheets-formula/src/locale/function-list/logical/en-US.ts+++ b/packages/sheets-formula/src/locale/function-list/logical/en-US.ts@@ -128,7 +128,7 @@ export default {},},LAMBDA: {- description: `Create custom, reusable functions and call them by a friendly name`,+ description: `Use a LAMBDA function to create custom, reusable functions and call them by a friendly name. The new function is available throughout the workbook and called like native Excel functions.`,abstract: `Create custom, reusable functions and call them by a friendly name`,links: [{@@ -137,8 +137,14 @@ export default {},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ parameter: {+ name: 'parameter',+ detail: 'A value that you want to pass to the function, such as a cell reference, string or number. You can enter up to 253 parameters. This argument is optional.',+ },+ calculation: {+ name: 'calculation',+ detail: 'The formula you want to execute and return as the result of the function. It must be the last argument and it must return a result. This argument is required.',+ },},},LET: {diff --git a/packages/sheets-formula/src/locale/function-list/logical/ja-JP.ts b/packages/sheets-formula/src/locale/function-list/logical/ja-JP.tsindex 97aff01292..4e8a9be63c 100644--- a/packages/sheets-formula/src/locale/function-list/logical/ja-JP.ts+++ b/packages/sheets-formula/src/locale/function-list/logical/ja-JP.ts@@ -128,7 +128,7 @@ export default {},},LAMBDA: {- description: `カスタムで再利用可能な関数を作成し、フレンドリ名で呼び出す`,+ description: `LAMBDA 関数を使用して、再利用可能なカスタム関数を作成し、フレンドリ名で呼び出します。 新しい関数はブック全体で使用でき、ネイティブ Excel 関数と同様に呼び出されます。`,abstract: `カスタムで再利用可能な関数を作成し、フレンドリ名で呼び出す`,links: [{@@ -137,8 +137,14 @@ export default {},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ parameter: {+ name: 'パラメーター',+ detail: 'セル参照、文字列、数値などの関数に渡す値。 最大 253 個のパラメーターを入力できます。 この引数は省略可能です。',+ },+ calculation: {+ name: '計算',+ detail: '関数の結果として実行して返す数式。 最後の引数である必要性があり、結果を返す必要があります。 この引数は必須です。',+ },},},LET: {diff --git a/packages/sheets-formula/src/locale/function-list/logical/zh-CN.ts b/packages/sheets-formula/src/locale/function-list/logical/zh-CN.tsindex 07a67baed9..135143236a 100644--- a/packages/sheets-formula/src/locale/function-list/logical/zh-CN.ts+++ b/packages/sheets-formula/src/locale/function-list/logical/zh-CN.ts@@ -128,7 +128,8 @@ export default {},},LAMBDA: {- description: '创建自定义、可重用的函数,并通过友好名称调用它们',+ description:+ '使用 LAMBDA 函数创建可重用的自定义函数,并使用易记名称调用它们。 新函数在整个工作簿中可用,其调用类似本机 Excel 函数。',abstract: '创建自定义、可重用的函数,并通过友好名称调用它们',links: [{@@ -137,8 +138,14 @@ export default {},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ parameter: {+ name: '参数',+ detail: '要传递给函数的值,例如单元格引用、字符串或数字。 最多可以输入 253 个参数。 此参数可选。',+ },+ calculation: {+ name: '计算',+ detail: '要作为函数结果执行并返回的公式。 其必须为最后一个参数,且必须返回结果。 此参数是必需项。',+ },},},LET: {diff --git a/packages/sheets-formula/src/locale/function-list/lookup/en-US.ts b/packages/sheets-formula/src/locale/function-list/lookup/en-US.tsindex 08dcfd6e87..9fd740173b 100644--- a/packages/sheets-formula/src/locale/function-list/lookup/en-US.ts+++ b/packages/sheets-formula/src/locale/function-list/lookup/en-US.ts@@ -470,7 +470,7 @@ export default {},},VLOOKUP: {- description: `Looks in the first column of an array and moves across the row to return the value of a cell`,+ description: `Use VLOOKUP when you need to find things in a table or a range by row. For example, look up a price of an automotive part by the part number, or find an employee name based on their employee ID.`,abstract: `Looks in the first column of an array and moves across the row to return the value of a cell`,links: [{@@ -479,8 +479,22 @@ export default {},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ lookupValue: {+ name: 'lookup_value',+ detail: 'The value you want to look up. The value you want to look up must be in the first column of the range of cells you specify in the table_array argument.',+ },+ tableArray: {+ name: 'table_array',+ detail: 'The range of cells in which the VLOOKUP will search for the lookup_value and the return value. You can use a named range or a table, and you can use names in the argument instead of cell references. ',+ },+ colIndexNum: {+ name: 'col_index_num',+ detail: 'The column number (starting with 1 for the left-most column of table_array) that contains the return value.',+ },+ rangeLookup: {+ name: 'range_lookup',+ detail: 'A logical value that specifies whether you want VLOOKUP to find an approximate or an exact match: Approximate match - 1/TRUE, Exact match - 0/FALSE',+ },},},VSTACK: {diff --git a/packages/sheets-formula/src/locale/function-list/lookup/ja-JP.ts b/packages/sheets-formula/src/locale/function-list/lookup/ja-JP.tsindex e14f70c18c..ae3eb4deae 100644--- a/packages/sheets-formula/src/locale/function-list/lookup/ja-JP.ts+++ b/packages/sheets-formula/src/locale/function-list/lookup/ja-JP.ts@@ -459,7 +459,7 @@ export default {},},VLOOKUP: {- description: `配列の左端列で特定の値を検索し、対応するセルの値を返します。`,+ description: `テーブルまたは範囲の内容を行ごとに検索する場合は、VLOOKUP を使用します。 たとえば、自動車部品の価格を部品番号で検索するか、従業員 ID に基づいて従業員名を検索します。`,abstract: `配列の左端列で特定の値を検索し、対応するセルの値を返します。`,links: [{@@ -468,8 +468,22 @@ export default {},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ lookupValue: {+ name: '検索値',+ detail: '検索の対象となる値。 調べたい値は、引数の 範囲 で指定したセル範囲の最初の列になければなりません。',+ },+ tableArray: {+ name: '範囲',+ detail: 'VLOOKUP が検索値と戻り値を検索するセル範囲。 名前付き範囲またはテーブルを使用でき、セル参照の代わりに引数に名前を使用できます。 ',+ },+ colIndexNum: {+ name: '列番号',+ detail: '戻り値を含む列の番号 (範囲 の左端の列は 1 で始まります)。',+ },+ rangeLookup: {+ name: '検索の型',+ detail: 'VLOOKUP を使用して、近似一致を検索するか、完全一致を検索するかを指定する論理値です。',+ },},},VSTACK: {diff --git a/packages/sheets-formula/src/locale/function-list/lookup/zh-CN.ts b/packages/sheets-formula/src/locale/function-list/lookup/zh-CN.tsindex f526e2696a..f751c6660d 100644--- a/packages/sheets-formula/src/locale/function-list/lookup/zh-CN.ts+++ b/packages/sheets-formula/src/locale/function-list/lookup/zh-CN.ts@@ -460,7 +460,8 @@ export default {},},VLOOKUP: {- description: '在数组第一列中查找,然后在行之间移动以返回单元格的值',+ description:+ '需要在表格或区域中按行查找内容时,请使用 VLOOKUP。 例如,按部件号查找汽车部件的价格,或根据员工 ID 查找员工姓名。',abstract: '在数组第一列中查找,然后在行之间移动以返回单元格的值',links: [{@@ -469,8 +470,22 @@ export default {},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ lookupValue: {+ name: 'lookup_value',+ detail: '要查找的值。 要查找的值必须位于 table_array 参数中指定的单元格区域的第一列中。',+ },+ tableArray: {+ name: 'table_array',+ detail: 'VLOOKUP 在其中搜索 lookup_value 和返回值的单元格区域。 可以使用命名区域或表,并且可以在参数中使用名称,而不是单元格引用。 ',+ },+ colIndexNum: {+ name: 'col_index_num',+ detail: '其中包含返回值的单元格的编号(table_array 最左侧单元格为 1 开始编号)。',+ },+ rangeLookup: {+ name: 'range_lookup',+ detail: '一个逻辑值,该值指定希望 VLOOKUP 查找近似匹配还是精确匹配:近似匹配 - 1/TRUE, 完全匹配 - 0/FALSE',+ },},},VSTACK: {diff --git a/packages/sheets-formula/src/services/function-list/array.ts b/packages/sheets-formula/src/services/function-list/array.tsindex 7d68b8fb4f..62a24bc73d 100644--- a/packages/sheets-formula/src/services/function-list/array.ts+++ b/packages/sheets-formula/src/services/function-list/array.ts@@ -14,37 +14,6 @@* limitations under the License.*/-import { FUNCTION_NAMES_ARRAY, FunctionType, type IFunctionInfo } from '@univerjs/engine-formula';+import { type IFunctionInfo } from '@univerjs/engine-formula';-export const FUNCTION_LIST_ARRAY: IFunctionInfo[] = [- {- functionName: FUNCTION_NAMES_ARRAY.MAKEARRAY,- aliasFunctionName: 'formula.functionList.MAKEARRAY.aliasFunctionName',- functionType: FunctionType.Array,- description: 'formula.functionList.MAKEARRAY.description',- abstract: 'formula.functionList.MAKEARRAY.abstract',- functionParameter: [- {- name: 'formula.functionList.MAKEARRAY.functionParameter.number1.name',- detail: 'formula.functionList.MAKEARRAY.functionParameter.number1.detail',- example: '8',- require: 1,- repeat: 0,- },- {- name: 'formula.functionList.MAKEARRAY.functionParameter.number2.name',- detail: 'formula.functionList.MAKEARRAY.functionParameter.number2.detail',- example: '7',- require: 1,- repeat: 0,- },- {- name: 'formula.functionList.MAKEARRAY.functionParameter.value3.name',- detail: 'formula.functionList.MAKEARRAY.functionParameter.value3.detail',- example: 'LAMBDA(r,c, r*c)',- require: 1,- repeat: 0,- },- ],- },-];+export const FUNCTION_LIST_ARRAY: IFunctionInfo[] = [];diff --git a/packages/sheets-formula/src/services/function-list/logical.ts b/packages/sheets-formula/src/services/function-list/logical.tsindex e66ec61bbf..f8efdb4285 100644--- a/packages/sheets-formula/src/services/function-list/logical.ts+++ b/packages/sheets-formula/src/services/function-list/logical.ts@@ -200,16 +200,16 @@ export const FUNCTION_LIST_LOGICAL: IFunctionInfo[] = [abstract: 'formula.functionList.LAMBDA.abstract',functionParameter: [{- name: 'formula.functionList.LAMBDA.functionParameter.number1.name',- detail: 'formula.functionList.LAMBDA.functionParameter.number1.detail',- example: 'A1:A20',+ name: 'formula.functionList.LAMBDA.functionParameter.parameter.name',+ detail: 'formula.functionList.LAMBDA.functionParameter.parameter.detail',+ example: '[x, y, …,]',require: 1,- repeat: 0,+ repeat: 1,},{- name: 'formula.functionList.LAMBDA.functionParameter.number2.name',- detail: 'formula.functionList.LAMBDA.functionParameter.number2.detail',- example: 'A1:A20',+ name: 'formula.functionList.LAMBDA.functionParameter.calculation.name',+ detail: 'formula.functionList.LAMBDA.functionParameter.calculation.detail',+ example: 'x+y',require: 1,repeat: 0,},@@ -239,6 +239,7 @@ export const FUNCTION_LIST_LOGICAL: IFunctionInfo[] = [},{functionName: FUNCTION_NAMES_LOGICAL.MAKEARRAY,+ aliasFunctionName: 'formula.functionList.MAKEARRAY.aliasFunctionName',functionType: FunctionType.Logical,description: 'formula.functionList.MAKEARRAY.description',abstract: 'formula.functionList.MAKEARRAY.abstract',@@ -246,14 +247,21 @@ export const FUNCTION_LIST_LOGICAL: IFunctionInfo[] = [{name: 'formula.functionList.MAKEARRAY.functionParameter.number1.name',detail: 'formula.functionList.MAKEARRAY.functionParameter.number1.detail',- example: 'A1:A20',+ example: '8',require: 1,repeat: 0,},{name: 'formula.functionList.MAKEARRAY.functionParameter.number2.name',detail: 'formula.functionList.MAKEARRAY.functionParameter.number2.detail',- example: 'A1:A20',+ example: '7',+ require: 1,+ repeat: 0,+ },+ {+ name: 'formula.functionList.MAKEARRAY.functionParameter.value3.name',+ detail: 'formula.functionList.MAKEARRAY.functionParameter.value3.detail',+ example: 'LAMBDA(r,c, r*c)',require: 1,repeat: 0,},diff --git a/packages/sheets-formula/src/services/function-list/lookup.ts b/packages/sheets-formula/src/services/function-list/lookup.tsindex f90968ee55..049d4e2688 100644--- a/packages/sheets-formula/src/services/function-list/lookup.ts+++ b/packages/sheets-formula/src/services/function-list/lookup.ts@@ -727,19 +727,33 @@ export const FUNCTION_LIST_LOOKUP: IFunctionInfo[] = [abstract: 'formula.functionList.VLOOKUP.abstract',functionParameter: [{- name: 'formula.functionList.VLOOKUP.functionParameter.number1.name',- detail: 'formula.functionList.VLOOKUP.functionParameter.number1.detail',- example: 'A1:A20',+ name: 'formula.functionList.VLOOKUP.functionParameter.lookupValue.name',+ detail: 'formula.functionList.VLOOKUP.functionParameter.lookupValue.detail',+ example: 'B2',require: 1,repeat: 0,},{- name: 'formula.functionList.VLOOKUP.functionParameter.number2.name',- detail: 'formula.functionList.VLOOKUP.functionParameter.number2.detail',- example: 'A1:A20',+ name: 'formula.functionList.VLOOKUP.functionParameter.tableArray.name',+ detail: 'formula.functionList.VLOOKUP.functionParameter.tableArray.detail',+ example: 'C2:E7',+ require: 1,+ repeat: 0,+ },+ {+ name: 'formula.functionList.VLOOKUP.functionParameter.colIndexNum.name',+ detail: 'formula.functionList.VLOOKUP.functionParameter.colIndexNum.detail',+ example: '1',require: 1,repeat: 0,},+ {+ name: 'formula.functionList.VLOOKUP.functionParameter.rangeLookup.name',+ detail: 'formula.functionList.VLOOKUP.functionParameter.rangeLookup.detail',+ example: 'TRUE',+ require: 0,+ repeat: 0,+ },],},{diff --git a/packages/sheets-ui/src/controllers/status-bar.controller.ts b/packages/sheets-ui/src/controllers/status-bar.controller.tsindex 28b841f10a..9d69bae2ed 100644--- a/packages/sheets-ui/src/controllers/status-bar.controller.ts+++ b/packages/sheets-ui/src/controllers/status-bar.controller.ts@@ -113,7 +113,7 @@ export class StatusBarController extends Disposable {return undefined;}const arrayValue = refs.map((ref) => {- return ref.toArrayValueObject();+ return ref.toArrayValueObject(false);});const res = executor?.calculate(...arrayValue) as BaseValueObject;if (!res.getValue) {