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
fix(formula): add OR/TEXT/LEN functions (#1593)
Dushusirc26eed129aed
diff --git a/packages/engine-formula/src/basics/date.ts b/packages/engine-formula/src/basics/date.tsindex 8762704942..9899592a3b 100644--- a/packages/engine-formula/src/basics/date.ts+++ b/packages/engine-formula/src/basics/date.ts@@ -14,7 +14,7 @@* limitations under the License.*/-export const DEFFAULT_DATE_FORMAT = 'yyyy-mm-dd;@';+export const DEFAULT_DATE_FORMAT = 'yyyy/mm/dd;@';/*** Excel stores dates as sequential serial numbers so they can be used in calculations. By default, January 1, 1900 is serial number 1, and January 1, 2008 is serial number 39448 because it is 39,447 days after January 1, 1900.diff --git a/packages/engine-formula/src/basics/object-class-type.ts b/packages/engine-formula/src/basics/object-class-type.tsindex 504538a8fc..b20d190e24 100644--- a/packages/engine-formula/src/basics/object-class-type.ts+++ b/packages/engine-formula/src/basics/object-class-type.ts@@ -23,6 +23,10 @@ export class ObjectClassType extends Disposable {return this.pattern;}+ /**+ * Only used in NumberValueObject+ * @param pattern+ */setPattern(pattern: string) {this.pattern = pattern;}diff --git a/packages/engine-formula/src/engine/ast-node/suffix-node.ts b/packages/engine-formula/src/engine/ast-node/suffix-node.tsindex a782086500..fc39539b9b 100644--- a/packages/engine-formula/src/engine/ast-node/suffix-node.ts+++ b/packages/engine-formula/src/engine/ast-node/suffix-node.ts@@ -65,7 +65,9 @@ export class SuffixNode extends BaseAstNode {) as FunctionVariantType;// set number format- result.setPattern('0.00%');+ if ((result as NumberValueObject).isNumber()) {+ result.setPattern('0.00%');+ }} else if (this._operatorString === suffixToken.POUND) {result = this._handlerPound(value);} else {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 29943fe5a6..a3d3b5c499 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@@ -172,9 +172,10 @@ export class BaseReferenceObject extends ObjectClassType {}const resultObjectValue = this.getCellValueObject(cell);+ const isNumber = resultObjectValue.isNumber();const pattern = this._numfmtItemData[unitId]?.[sheetId]?.[r]?.[c];- pattern && resultObjectValue.setPattern(pattern);+ pattern && isNumber && resultObjectValue.setPattern(pattern);result = callback(resultObjectValue, r, c);@@ -194,12 +195,13 @@ export class BaseReferenceObject extends ObjectClassType {}const cellValueObject = this.getCellValueObject(cell);+ const isNumber = cellValueObject.isNumber();// Set numfmt patternconst unitId = this._forcedUnitId || this._defaultUnitId;const sheetId = this._forcedSheetId || this._defaultSheetId;const numfmtItem = this._numfmtItemData[unitId]?.[sheetId]?.[startRow]?.[startColumn];- numfmtItem && cellValueObject.setPattern(numfmtItem);+ numfmtItem && isNumber && cellValueObject.setPattern(numfmtItem);return cellValueObject;}diff --git a/packages/engine-formula/src/engine/utils/char-kit.ts b/packages/engine-formula/src/engine/utils/char-kit.tsnew file mode 100644index 0000000000..3e22a03670--- /dev/null+++ b/packages/engine-formula/src/engine/utils/char-kit.ts@@ -0,0 +1,44 @@+/**+ * 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.+ */++/**+ * Korean in Excel does not count as two characters. Here we calculate all Chinese, Japanese and Korean characters as two characters.+ *+ * ā -> 1+ * ー -> 2+ *+ * @param str+ * @returns+ */+export function charLenByte(str: string) {+ let byteCount = 0;++ for (let i = 0; i < str.length; i++) {+ const charCode = str.charCodeAt(i);++ if (+ (charCode >= 0x3040 && charCode <= 0x30FF) || // Japanese hiragana and katakana+ (charCode >= 0x4E00 && charCode <= 0x9FFF) || // Chinese (simplified and traditional)+ (charCode >= 0xAC00 && charCode <= 0xD7AF) // Korean language+ ) {+ byteCount += 2;+ } else {+ byteCount += 1;+ }+ }++ return byteCount;+}diff --git a/packages/engine-formula/src/engine/value-object/primitive-object.ts b/packages/engine-formula/src/engine/value-object/primitive-object.tsindex 0304282ffe..b9b870eb82 100644--- a/packages/engine-formula/src/engine/value-object/primitive-object.ts+++ b/packages/engine-formula/src/engine/value-object/primitive-object.ts@@ -459,8 +459,10 @@ export class NumberValueObject extends BaseValueObject {return (o as BaseValueObject).plus(this);}const object = this.minusBy(valueObject.getValue());++ // = 1 - #NAME? gets #NAME?, = 1 - #VALUE! gets #VALUE!if (object.isError()) {- return this;+ return object;}// Set number format@@ -475,6 +477,11 @@ export class NumberValueObject extends BaseValueObject {}const object = this.multiplyBy(valueObject.getValue());+ // = 1 * #NAME? gets #NAME?, = 1 * #VALUE! gets #VALUE!+ if (object.isError()) {+ return object;+ }+// Set number formatobject.setPattern(this.getPattern() || valueObject.getPattern());@@ -491,6 +498,11 @@ export class NumberValueObject extends BaseValueObject {}const object = this.dividedBy(valueObject.getValue());+ // = 1 / #NAME? gets #NAME?, = 1 / #VALUE! gets #VALUE!+ if (object.isError()) {+ return object;+ }+// Set number formatobject.setPattern(this.getPattern() || valueObject.getPattern());diff --git a/packages/engine-formula/src/functions/date/date/index.ts b/packages/engine-formula/src/functions/date/date/index.tsindex 56fb857c04..a0008b81d9 100644--- a/packages/engine-formula/src/functions/date/date/index.ts+++ b/packages/engine-formula/src/functions/date/date/index.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import { DEFFAULT_DATE_FORMAT, excelDateSerial } from '../../../basics/date';+import { DEFAULT_DATE_FORMAT, excelDateSerial } from '../../../basics/date';import { ErrorType } from '../../../basics/error-type';import { expandArrayValueObject } from '../../../engine/utils/array-object';import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';@@ -100,7 +100,7 @@ export class DateFunction extends BaseFunction {}const valueObject = NumberValueObject.create(currentSerial);- valueObject.setPattern(DEFFAULT_DATE_FORMAT);+ valueObject.setPattern(DEFAULT_DATE_FORMAT);return valueObject;});diff --git a/packages/engine-formula/src/functions/date/edate/index.ts b/packages/engine-formula/src/functions/date/edate/index.tsindex 35b1b87fc3..7ae241ba7b 100644--- a/packages/engine-formula/src/functions/date/edate/index.ts+++ b/packages/engine-formula/src/functions/date/edate/index.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import { DEFFAULT_DATE_FORMAT, excelDateSerial, excelSerialToDate } from '../../../basics/date';+import { DEFAULT_DATE_FORMAT, excelDateSerial, excelSerialToDate } from '../../../basics/date';import { ErrorType } from '../../../basics/error-type';import { expandArrayValueObject } from '../../../engine/utils/array-object';import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';@@ -88,7 +88,7 @@ export class Edate extends BaseFunction {const currentSerial = excelDateSerial(resultDate);const valueObject = NumberValueObject.create(currentSerial);- valueObject.setPattern(DEFFAULT_DATE_FORMAT);+ valueObject.setPattern(DEFAULT_DATE_FORMAT);return valueObject;});diff --git a/packages/engine-formula/src/functions/date/today/index.ts b/packages/engine-formula/src/functions/date/today/index.tsindex 0674677de5..1aab50cb9d 100644--- a/packages/engine-formula/src/functions/date/today/index.ts+++ b/packages/engine-formula/src/functions/date/today/index.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import { DEFFAULT_DATE_FORMAT, excelDateSerial } from '../../../basics/date';+import { DEFAULT_DATE_FORMAT, excelDateSerial } from '../../../basics/date';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';@@ -29,7 +29,7 @@ export class Today extends BaseFunction {const currentSerial = excelDateSerial(new Date());const valueObject = NumberValueObject.create(currentSerial);- valueObject.setPattern(DEFFAULT_DATE_FORMAT);+ valueObject.setPattern(DEFAULT_DATE_FORMAT);return valueObject;}}diff --git a/packages/engine-formula/src/functions/logical/function-map.ts b/packages/engine-formula/src/functions/logical/function-map.tsindex e0204f42ed..40fb16a3af 100644--- a/packages/engine-formula/src/functions/logical/function-map.ts+++ b/packages/engine-formula/src/functions/logical/function-map.ts@@ -20,11 +20,13 @@ import { If } from './if';import { Iferror } from './iferror';import { Lambda } from './lambda';import { Makearray } from './makearray';+import { Or } from './or';export const functionLogical = [[And, FUNCTION_NAMES_LOGICAL.AND],+ [If, FUNCTION_NAMES_LOGICAL.IF],[Lambda, FUNCTION_NAMES_LOGICAL.LAMBDA],[Makearray, FUNCTION_NAMES_LOGICAL.MAKEARRAY],- [If, FUNCTION_NAMES_LOGICAL.IF],+ [Or, FUNCTION_NAMES_LOGICAL.OR],[Iferror, FUNCTION_NAMES_LOGICAL.IFERROR],];diff --git a/packages/engine-formula/src/functions/logical/or/__tests__/index.spec.ts b/packages/engine-formula/src/functions/logical/or/__tests__/index.spec.tsnew file mode 100644index 0000000000..801fbfa8dd--- /dev/null+++ b/packages/engine-formula/src/functions/logical/or/__tests__/index.spec.ts@@ -0,0 +1,140 @@+/**+ * 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 { FUNCTION_NAMES_LOGICAL } from '../../function-names';+import { Or } from '..';+import { ArrayValueObject, transformToValueObject } from '../../../../engine/value-object/array-value-object';+import { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';+import { ErrorType } from '../../../..';++describe('Test or function', () => {+ const textFunction = new Or(FUNCTION_NAMES_LOGICAL.OR);++ describe('Or', () => {+ it('logical1 string', () => {+ const logical1 = StringValueObject.create('a1');+ const result = textFunction.calculate(logical1);+ expect(result.getValue()).toBe(ErrorType.VALUE);+ });+ it('logical1 number 1', () => {+ const logical1 = NumberValueObject.create(1);+ const result = textFunction.calculate(logical1);+ expect(result.getValue()).toBe(true);+ });++ it('logical1 number 0', () => {+ const logical1 = NumberValueObject.create(0);+ const result = textFunction.calculate(logical1);+ expect(result.getValue()).toBe(false);+ });++ it('logical1 null', () => {+ const logical1 = NullValueObject.create();+ const result = textFunction.calculate(logical1);+ expect(result.getValue()).toBe(ErrorType.VALUE);+ });++ it('logical1 true', () => {+ const logical1 = BooleanValueObject.create(true);+ const result = textFunction.calculate(logical1);+ expect(result.getValue()).toBe(true);+ });++ it('logical2 false', () => {+ const logical1 = BooleanValueObject.create(true);+ const logical2 = BooleanValueObject.create(false);+ const result = textFunction.calculate(logical1, logical2);+ expect(result.getValue()).toBe(true);+ });++ it('logical1 is array, no logical value', () => {+ const logical1 = ArrayValueObject.create({+ calculateValueList: transformToValueObject([+ ['a1'],+ ['a2'],+ ]),+ rowCount: 2,+ columnCount: 1,+ unitId: '',+ sheetId: '',+ row: 0,+ column: 0,+ });+ const result = textFunction.calculate(logical1);+ expect(result.getValue()).toBe(ErrorType.VALUE);+ });++ it('logical1 is array and logical2 is array', () => {+ const logical1 = ArrayValueObject.create({+ calculateValueList: transformToValueObject([+ ['a1'],+ ['a2'],+ ]),+ rowCount: 2,+ columnCount: 1,+ unitId: '',+ sheetId: '',+ row: 0,+ column: 0,+ });+ const logical2 = ArrayValueObject.create({+ calculateValueList: transformToValueObject([+ [true],+ ['a4'],+ ]),+ rowCount: 2,+ columnCount: 1,+ unitId: '',+ sheetId: '',+ row: 0,+ column: 0,+ });+ const result = textFunction.calculate(logical1, logical2);+ expect(result.getValue()).toBe(true);+ });++ it('logical1 is array and logical2 is array, error value', () => {+ const logical1 = ArrayValueObject.create({+ calculateValueList: transformToValueObject([+ ['a1'],+ ['a2'],+ ]),+ rowCount: 2,+ columnCount: 1,+ unitId: '',+ sheetId: '',+ row: 0,+ column: 0,+ });+ const logical2 = ArrayValueObject.create({+ calculateValueList: transformToValueObject([+ [false],+ ['#NAME?'],+ ]),+ rowCount: 2,+ columnCount: 1,+ unitId: '',+ sheetId: '',+ row: 0,+ column: 0,+ });+ const result = textFunction.calculate(logical1, logical2);+ expect(result.getValue()).toBe('#NAME?');+ });+ });+});diff --git a/packages/engine-formula/src/functions/logical/or/index.ts b/packages/engine-formula/src/functions/logical/or/index.tsnew file mode 100644index 0000000000..12e2095ab1--- /dev/null+++ b/packages/engine-formula/src/functions/logical/or/index.ts@@ -0,0 +1,60 @@+/**+ * 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 { ArrayValueObject } from '../../../engine/value-object/array-value-object';+import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';+import { BooleanValueObject } from '../../../engine/value-object/primitive-object';+import { BaseFunction } from '../../base-function';++export class Or extends BaseFunction {+ override calculate(...logicalValues: BaseValueObject[]) {+ if (logicalValues.length === 0) {+ return new ErrorValueObject(ErrorType.NA);+ }++ let result = false;+ let noBoolean = true;+ let errorValue = null;++ for (const logicalValue of logicalValues) {+ if (logicalValue.isError()) {+ return logicalValue;+ }++ if (logicalValue.isArray()) {+ (logicalValue as ArrayValueObject).iterator((value) => {+ if (value?.isError()) {+ errorValue = value;+ return false;+ } else if (value?.isBoolean() || value?.isNumber()) {+ result = result || !!value.getValue();+ noBoolean = false;+ }+ });++ if (errorValue) {+ return errorValue;+ }+ } else if (logicalValue.isBoolean() || logicalValue.isNumber()) {+ result = result || !!logicalValue.getValue();+ noBoolean = false;+ }+ }++ return noBoolean ? new ErrorValueObject(ErrorType.VALUE) : new BooleanValueObject(result);+ }+}diff --git a/packages/engine-formula/src/functions/text/function-map.ts b/packages/engine-formula/src/functions/text/function-map.tsindex 5273ac82af..b11c41c206 100644--- a/packages/engine-formula/src/functions/text/function-map.ts+++ b/packages/engine-formula/src/functions/text/function-map.ts@@ -16,5 +16,13 @@import { Concatenate } from './concatenate';import { FUNCTION_NAMES_TEXT } from './function-names';+import { Len } from './len';+import { Lenb } from './lenb';+import { Text } from './text';-export const functionText = [[Concatenate, FUNCTION_NAMES_TEXT.CONCATENATE]];+export const functionText = [+ [Concatenate, FUNCTION_NAMES_TEXT.CONCATENATE],+ [Len, FUNCTION_NAMES_TEXT.LEN],+ [Lenb, FUNCTION_NAMES_TEXT.LENB],+ [Text, FUNCTION_NAMES_TEXT.TEXT],+];diff --git a/packages/engine-formula/src/functions/text/len/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/len/__test__/index.spec.tsnew file mode 100644index 0000000000..86cd19266c--- /dev/null+++ b/packages/engine-formula/src/functions/text/len/__test__/index.spec.ts@@ -0,0 +1,82 @@+/**+ * 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 { FUNCTION_NAMES_TEXT } from '../../function-names';+import { Len } from '..';+import { StringValueObject } from '../../../../engine/value-object/primitive-object';+import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';+import { ErrorType } from '../../../../basics/error-type';++describe('Test len function', () => {+ const textFunction = new Len(FUNCTION_NAMES_TEXT.LEN);++ describe('Len', () => {+ it('Text is single cell', () => {+ const text = StringValueObject.create('Univer');+ const result = textFunction.calculate(text);+ expect(result.getValue()).toStrictEqual(6);+ });++ it('Text1 is array', () => {+ const text = new ArrayValueObject({+ calculateValueList: transformToValueObject([+ [1, ' ', 1.23, true, false, null, 'Univer表格シート繁體한국인'],+ [0, '100', '2.34', 'test', -3, ErrorType.VALUE, null],+ ]),+ rowCount: 2,+ columnCount: 7,+ unitId: '',+ sheetId: '',+ row: 0,+ column: 0,+ });+ const result = textFunction.calculate(text);+ expect(transformToValue(result.getArrayValue())).toStrictEqual([+ [1, 1, 4, 4, 5, 0, 16],+ [1, 3, 4, 4, 2, '#VALUE!', 0],+ ]);+ });+ it('Text1 is array with emoji', () => {+ const text = new ArrayValueObject({+ calculateValueList: transformToValueObject([+ ['u'],+ [1],+ ['ß'],+ ['é'],+ ['ع'],+ ['汉'],+ ['漢'],+ ['😊'],+ ['𐌸'],+ ['👨👩👧'],+ ['𓀀'],+ ['𐌰'],+ ['♚'],+ ]),+ rowCount: 13,+ columnCount: 1,+ unitId: '',+ sheetId: '',+ row: 0,+ column: 0,+ });+ const result = textFunction.calculate(text);+ expect(transformToValue(result.getArrayValue())).toStrictEqual([[1], [1], [1], [1], [1], [1], [1], [2], [2], [8], [2], [2], [1]]);+ });+ });+});diff --git a/packages/engine-formula/src/functions/text/len/index.ts b/packages/engine-formula/src/functions/text/len/index.tsnew file mode 100644index 0000000000..91f31fb3ad--- /dev/null+++ b/packages/engine-formula/src/functions/text/len/index.ts@@ -0,0 +1,57 @@+/**+ * 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 { NumberValueObject } from '../../../engine/value-object/primitive-object';+import { BaseFunction } from '../../base-function';++export class Len extends BaseFunction {+ override calculate(text: BaseValueObject) {+ if (text == null) {+ return ErrorValueObject.create(ErrorType.NA);+ }++ if (text.isError()) {+ return text;+ }++ if (text.isArray()) {+ return text.mapValue((textValue: BaseValueObject) => {+ return this._handleSingleText(textValue);+ });+ }++ return this._handleSingleText(text);+ }++ private _handleSingleText(text: BaseValueObject) {+ if (text.isError()) {+ return text;+ }++ if (text.isNull()) {+ return NumberValueObject.create(0);+ }++ if (text.isString() || text.isBoolean() || text.isNumber()) {+ const textValue = text.getValue().toString();+ return NumberValueObject.create(textValue.length);+ }++ return ErrorValueObject.create(ErrorType.VALUE);+ }+}diff --git a/packages/engine-formula/src/functions/text/lenb/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/lenb/__test__/index.spec.tsnew file mode 100644index 0000000000..70cf5e6e7b--- /dev/null+++ b/packages/engine-formula/src/functions/text/lenb/__test__/index.spec.ts@@ -0,0 +1,83 @@+/**+ * 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 { FUNCTION_NAMES_TEXT } from '../../function-names';+import { Lenb } from '..';+import { StringValueObject } from '../../../../engine/value-object/primitive-object';+import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';+import { ErrorType } from '../../../../basics/error-type';++describe('Test lenb function', () => {+ const textFunction = new Lenb(FUNCTION_NAMES_TEXT.LENB);++ describe('Lenb', () => {+ it('Text is single cell', () => {+ const text = StringValueObject.create('Univer');+ const result = textFunction.calculate(text);+ expect(result.getValue()).toStrictEqual(6);+ });++ it('Text1 is array', () => {+ const text = new ArrayValueObject({+ calculateValueList: transformToValueObject([+ [1, ' ', 1.23, true, false, null, 'Univer表格シート繁體한국인'],+ [0, '100', '2.34', 'test', -3, ErrorType.VALUE, null],+ ]),+ rowCount: 2,+ columnCount: 7,+ unitId: '',+ sheetId: '',+ row: 0,+ column: 0,+ });+ const result = textFunction.calculate(text);+ expect(transformToValue(result.getArrayValue())).toStrictEqual([+ [1, 1, 4, 4, 5, 0, 26],+ [1, 3, 4, 4, 2, '#VALUE!', 0],+ ]);+ });++ it('Text1 is array with emoji', () => {+ const text = new ArrayValueObject({+ calculateValueList: transformToValueObject([+ ['u'],+ [1],+ ['ß'],+ ['é'],+ ['ع'],+ ['汉'],+ ['漢'],+ ['😊'],+ ['𐌸'],+ ['👨👩👧'],+ ['𓀀'],+ ['𐌰'],+ ['♚'],+ ]),+ rowCount: 13,+ columnCount: 1,+ unitId: '',+ sheetId: '',+ row: 0,+ column: 0,+ });+ const result = textFunction.calculate(text);+ expect(transformToValue(result.getArrayValue())).toStrictEqual([[1], [1], [1], [1], [1], [2], [2], [2], [2], [8], [2], [2], [1]]);+ });+ });+});diff --git a/packages/engine-formula/src/functions/text/lenb/index.ts b/packages/engine-formula/src/functions/text/lenb/index.tsnew file mode 100644index 0000000000..51cde5c20c--- /dev/null+++ b/packages/engine-formula/src/functions/text/lenb/index.ts@@ -0,0 +1,60 @@+/**+ * 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 { charLenByte } from '../../../engine/utils/char-kit';+import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';+import { NumberValueObject } from '../../../engine/value-object/primitive-object';+import { BaseFunction } from '../../base-function';++export class Lenb extends BaseFunction {+ override calculate(text: BaseValueObject) {+ if (text == null) {+ return ErrorValueObject.create(ErrorType.NA);+ }++ if (text.isError()) {+ return text;+ }++ if (text.isArray()) {+ return text.mapValue((textValue: BaseValueObject) => {+ return this._handleSingleText(textValue);+ });+ }++ return this._handleSingleText(text);+ }++ private _handleSingleText(text: BaseValueObject) {+ if (text.isError()) {+ return text;+ }++ if (text.isNull()) {+ return NumberValueObject.create(0);+ }++ if (text.isString() || text.isBoolean() || text.isNumber()) {+ const textValue = text.getValue().toString();+ const textByteLen = charLenByte(textValue);++ return NumberValueObject.create(textByteLen);+ }++ return ErrorValueObject.create(ErrorType.VALUE);+ }+}diff --git a/packages/engine-formula/src/functions/text/text/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/text/__test__/index.spec.tsnew file mode 100644index 0000000000..e8fd6d895a--- /dev/null+++ b/packages/engine-formula/src/functions/text/text/__test__/index.spec.ts@@ -0,0 +1,38 @@+/**+ * 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 { FUNCTION_NAMES_TEXT } from '../../function-names';+import { Text } from '..';+import { NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';+import type { ArrayValueObject } from '../../../../engine/value-object/array-value-object';+import { transformToValue } from '../../../../engine/value-object/array-value-object';++describe('Test text function', () => {+ const textFunction = new Text(FUNCTION_NAMES_TEXT.TEXT);++ describe('Text', () => {+ it('Text is single cell, format text is single cell', () => {+ const text1 = NumberValueObject.create(111);+ const formatText = StringValueObject.create('$#,##0.00');+ const result = textFunction.calculate(text1, formatText);+ const resultArray = result.getArrayValue();+ expect(transformToValue(resultArray)).toStrictEqual([[111]]);+ expect((result as ArrayValueObject).getFirstCell().getPattern()).toStrictEqual('$#,##0.00');+ });+ });+});diff --git a/packages/engine-formula/src/functions/text/text/index.ts b/packages/engine-formula/src/functions/text/text/index.tsnew file mode 100644index 0000000000..504946c2bd--- /dev/null+++ b/packages/engine-formula/src/functions/text/text/index.ts@@ -0,0 +1,83 @@+/**+ * 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 { 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';+import { NumberValueObject, StringValueObject } from '../../../engine/value-object/primitive-object';+import { BaseFunction } from '../../base-function';++export class Text extends BaseFunction {+ override calculate(text: BaseValueObject, formatText: BaseValueObject) {+ if (text == null || formatText == null) {+ return ErrorValueObject.create(ErrorType.NA);+ }++ if (text.isError()) {+ return text;+ }++ if (formatText.isError()) {+ return formatText;+ }++ // get max row length+ const maxRowLength = Math.max(+ text.isArray() ? (text as ArrayValueObject).getRowCount() : 1,+ formatText.isArray() ? (formatText as ArrayValueObject).getRowCount() : 1+ );++ // get max column length+ const maxColumnLength = Math.max(+ text.isArray() ? (text as ArrayValueObject).getColumnCount() : 1,+ formatText.isArray() ? (formatText as ArrayValueObject).getColumnCount() : 1+ );++ const textArray = expandArrayValueObject(maxRowLength, maxColumnLength, text);+ const formatTextArray = expandArrayValueObject(maxRowLength, maxColumnLength, formatText);++ return textArray.map((textValue, rowIndex, columnIndex) => {+ if (textValue.isError() || textValue.isString() || textValue.isBoolean()) {+ return textValue;+ }++ let formatTextValue = formatTextArray.get(rowIndex, columnIndex);++ if (formatTextValue.isError()) {+ return formatTextValue;+ }++ if (formatTextValue.isBoolean()) {+ return ErrorValueObject.create(ErrorType.VALUE);+ }++ if (formatTextValue.isNull()) {+ formatTextValue = StringValueObject.create(' ');+ }++ const formatTextValueString = `${formatTextValue.getValue()}`;++ if (textValue.isNull()) {+ textValue = NumberValueObject.create(0);+ }++ const textValueNumber = textValue.getValue() as number;++ return NumberValueObject.create(textValueNumber, formatTextValueString);+ });+ }+}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 c3b371a401..2262a4c8e3 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@@ -215,7 +215,7 @@ export default {},},OR: {- description: 'Returns TRUE if any argument is TRUE',+ description: 'Returns TRUE if any of its arguments evaluate to TRUE, and returns FALSE if all of its arguments evaluate to FALSE.',abstract: 'Returns TRUE if any argument is TRUE',links: [{@@ -224,8 +224,8 @@ export default {},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ logical1: { name: 'logical1', detail: 'The first condition that you want to test that can evaluate to either TRUE or FALSE.' },+ logical2: { name: 'logical2', detail: 'Additional conditions that you want to test that can evaluate to either TRUE or FALSE, up to a maximum of 255 conditions.' },},},REDUCE: {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 ec251ccc29..298646894d 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@@ -209,7 +209,7 @@ export default {},},OR: {- description: 'いずれかの引数が TRUE のときに TRUE を返します。',+ description: 'OR 関数は、いずれかの引数が TRUE と評価された場合は TRUE を返し、すべての引数が FALSE と評価された場合は FALSE を返します。',abstract: 'いずれかの引数が TRUE のときに TRUE を返します。',links: [{@@ -218,8 +218,8 @@ export default {},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ logical1: { name: '論理式 1', detail: 'TRUE または FALSE に評価できるテスト対象の 1 つ目の条件。' },+ logical2: { name: '論理式 2', detail: '最大 255 個の条件まで、TRUE または FALSE のいずれかに評価できるテストする追加の条件。' },},},REDUCE: {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 995572221e..b03430334e 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@@ -210,7 +210,7 @@ export default {},},OR: {- description: '如果任一参数为 TRUE,则返回 TRUE',+ description: '如果 OR 函数的任意参数计算为 TRUE,则其返回 TRUE;如果其所有参数均计算机为 FALSE,则返回 FALSE。',abstract: '如果任一参数为 TRUE,则返回 TRUE',links: [{@@ -219,8 +219,8 @@ export default {},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ logical1: { name: '逻辑表达式 1', detail: '第一个想要测试且计算结果可为 TRUE 或 FALSE 的条件。' },+ logical2: { name: '逻辑表达式 2', detail: '其他想要测试且计算结果可为 TRUE 或 FALSE 的条件(最多 255 个条件)。' },},},REDUCE: {diff --git a/packages/sheets-formula/src/locale/function-list/text/en-US.ts b/packages/sheets-formula/src/locale/function-list/text/en-US.tsindex d4ce36a553..10d1513da7 100644--- a/packages/sheets-formula/src/locale/function-list/text/en-US.ts+++ b/packages/sheets-formula/src/locale/function-list/text/en-US.ts@@ -249,13 +249,12 @@ export default {},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ text: { name: 'text', detail: 'The text whose length you want to find. Spaces count as characters.' },},},LENB: {- description: 'Returns the number of characters in a text string',- abstract: 'Returns the number of characters in a text string',+ description: 'Returns the number of bytes used to represent the characters in a text string.',+ abstract: 'Returns the number of bytes used to represent the characters in a text string',links: [{title: 'Instruction',@@ -263,8 +262,7 @@ export default {},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ text: { name: 'text', detail: 'The text whose length you want to find. Spaces count as characters.' },},},LOWER: {@@ -487,8 +485,8 @@ export default {},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ value: { name: 'value', detail: 'A numeric value that you want to be converted into text.' },+ formatText: { name: 'format_text', detail: 'A text string that defines the formatting that you want to be applied to the supplied value.' },},},TEXTAFTER: {diff --git a/packages/sheets-formula/src/locale/function-list/text/ja-JP.ts b/packages/sheets-formula/src/locale/function-list/text/ja-JP.tsindex 97695294c3..9e51d68679 100644--- a/packages/sheets-formula/src/locale/function-list/text/ja-JP.ts+++ b/packages/sheets-formula/src/locale/function-list/text/ja-JP.ts@@ -241,8 +241,8 @@ export default {},},LEN: {- description: '文字列に含まれる文字数を返します。',- abstract: '文字列に含まれる文字数を返します。',+ description: 'は、文字列の文字数を返します。',+ abstract: 'は、文字列の文字数を返します。',links: [{title: '指導',@@ -250,13 +250,12 @@ export default {},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ text: { name: 'text', detail: '文字数またはバイト数を調べる文字列を指定します。 スペースは文字として数えられます。' },},},LENB: {- description: '文字列に含まれる文字数を返します。',- abstract: '文字列に含まれる文字数を返します。',+ description: 'は、文字列のバイト数を返します。',+ abstract: 'は、文字列のバイト数を返します。',links: [{title: '指導',@@ -264,8 +263,7 @@ export default {},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ text: { name: 'text', detail: '文字数またはバイト数を調べる文字列を指定します。 スペースは文字として数えられます。' },},},LOWER: {@@ -488,8 +486,8 @@ export default {},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ value: { name: '値', detail: 'テキストに変換する数値。' },+ formatText: { name: '数値形式', detail: '指定された値に適用する書式を定義するテキスト文字列。' },},},TEXTAFTER: {diff --git a/packages/sheets-formula/src/locale/function-list/text/zh-CN.ts b/packages/sheets-formula/src/locale/function-list/text/zh-CN.tsindex db356b9438..6f427e3f22 100644--- a/packages/sheets-formula/src/locale/function-list/text/zh-CN.ts+++ b/packages/sheets-formula/src/locale/function-list/text/zh-CN.ts@@ -249,13 +249,12 @@ export default {},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ text: { name: 'text', detail: '要查找其长度的文本。 空格将作为字符进行计数。' },},},LENB: {- description: '返回文本字符串中的字符个数',- abstract: '返回文本字符串中的字符个数',+ description: '返回文本字符串中用于代表字符的字节数。',+ abstract: '返回文本字符串中用于代表字符的字节数',links: [{title: '教学',@@ -263,8 +262,7 @@ export default {},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ text: { name: 'text', detail: ' 要查找其长度的文本。 空格将作为字符进行计数。' },},},LOWER: {@@ -487,8 +485,8 @@ export default {},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ value: { name: '值', detail: '要转换为文本的数值。' },+ formatText: { name: '数字格式', detail: '一个文本字符串,定义要应用于所提供值的格式。' },},},TEXTAFTER: {diff --git a/packages/sheets-formula/src/services/function-list/logical.ts b/packages/sheets-formula/src/services/function-list/logical.tsindex bd8b741799..714c29df5e 100644--- a/packages/sheets-formula/src/services/function-list/logical.ts+++ b/packages/sheets-formula/src/services/function-list/logical.ts@@ -325,18 +325,18 @@ export const FUNCTION_LIST_LOGICAL: IFunctionInfo[] = [abstract: 'formula.functionList.OR.abstract',functionParameter: [{- name: 'formula.functionList.OR.functionParameter.number1.name',- detail: 'formula.functionList.OR.functionParameter.number1.detail',- example: 'A1:A20',+ name: 'formula.functionList.OR.functionParameter.logical1.name',+ detail: 'formula.functionList.OR.functionParameter.logical1.detail',+ example: 'A1=1',require: 1,repeat: 0,},{- name: 'formula.functionList.OR.functionParameter.number2.name',- detail: 'formula.functionList.OR.functionParameter.number2.detail',- example: 'A1:A20',- require: 1,- repeat: 0,+ name: 'formula.functionList.OR.functionParameter.logical2.name',+ detail: 'formula.functionList.OR.functionParameter.logical2.detail',+ example: 'A2=2',+ require: 0,+ repeat: 1,},],},diff --git a/packages/sheets-formula/src/services/function-list/text.ts b/packages/sheets-formula/src/services/function-list/text.tsindex 3ffd99beb1..09ec334ac7 100644--- a/packages/sheets-formula/src/services/function-list/text.ts+++ b/packages/sheets-formula/src/services/function-list/text.ts@@ -376,16 +376,9 @@ export const FUNCTION_LIST_TEXT: IFunctionInfo[] = [abstract: 'formula.functionList.LEN.abstract',functionParameter: [{- name: 'formula.functionList.LEN.functionParameter.number1.name',- detail: 'formula.functionList.LEN.functionParameter.number1.detail',- example: 'A1:A20',- require: 1,- repeat: 0,- },- {- name: 'formula.functionList.LEN.functionParameter.number2.name',- detail: 'formula.functionList.LEN.functionParameter.number2.detail',- example: 'A1:A20',+ name: 'formula.functionList.LEN.functionParameter.text.name',+ detail: 'formula.functionList.LEN.functionParameter.text.detail',+ example: '"Univer"',require: 1,repeat: 0,},@@ -398,16 +391,9 @@ export const FUNCTION_LIST_TEXT: IFunctionInfo[] = [abstract: 'formula.functionList.LENB.abstract',functionParameter: [{- name: 'formula.functionList.LENB.functionParameter.number1.name',- detail: 'formula.functionList.LENB.functionParameter.number1.detail',- example: 'A1:A20',- require: 1,- repeat: 0,- },- {- name: 'formula.functionList.LENB.functionParameter.number2.name',- detail: 'formula.functionList.LENB.functionParameter.number2.detail',- example: 'A1:A20',+ name: 'formula.functionList.LENB.functionParameter.text.name',+ detail: 'formula.functionList.LENB.functionParameter.text.detail',+ example: '"Univer"',require: 1,repeat: 0,},@@ -750,16 +736,16 @@ export const FUNCTION_LIST_TEXT: IFunctionInfo[] = [abstract: 'formula.functionList.TEXT.abstract',functionParameter: [{- name: 'formula.functionList.TEXT.functionParameter.number1.name',- detail: 'formula.functionList.TEXT.functionParameter.number1.detail',- example: 'A1:A20',+ name: 'formula.functionList.TEXT.functionParameter.value.name',+ detail: 'formula.functionList.TEXT.functionParameter.value.detail',+ example: '1.23',require: 1,repeat: 0,},{- name: 'formula.functionList.TEXT.functionParameter.number2.name',- detail: 'formula.functionList.TEXT.functionParameter.number2.detail',- example: 'A1:A20',+ name: 'formula.functionList.TEXT.functionParameter.formatText.name',+ detail: 'formula.functionList.TEXT.functionParameter.formatText.detail',+ example: '"$0.00"',require: 1,repeat: 0,},