Skip to content

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

feat(formula): add function leftb (#3418)

Dushusirb66e8ce2e632
diff --git a/packages/engine-formula/src/functions/text/function-map.ts b/packages/engine-formula/src/functions/text/function-map.ts
index 9bf2eca2a4..d7f9281277 100644
--- a/packages/engine-formula/src/functions/text/function-map.ts
+++ b/packages/engine-formula/src/functions/text/function-map.ts
@@ -14,9 +14,10 @@
* limitations under the License.
*/
-import { FUNCTION_NAMES_TEXT } from './function-names';
import { Concat } from './concat';
import { Concatenate } from './concatenate';
+import { FUNCTION_NAMES_TEXT } from './function-names';
+import { Leftb } from './leftb';
import { Len } from './len';
import { Lenb } from './lenb';
import { Lower } from './lower';
@@ -37,4 +38,5 @@ export const functionText = [
[Textafter, FUNCTION_NAMES_TEXT.TEXTAFTER],
[Textbefore, FUNCTION_NAMES_TEXT.TEXTBEFORE],
[Textsplit, FUNCTION_NAMES_TEXT.TEXTSPLIT],
+ [Leftb, FUNCTION_NAMES_TEXT.LEFTB],
];
diff --git a/packages/engine-formula/src/functions/text/leftb/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/leftb/__test__/index.spec.ts
new file mode 100644
index 0000000000..e179b7574c
--- /dev/null
+++ b/packages/engine-formula/src/functions/text/leftb/__test__/index.spec.ts
@@ -0,0 +1,269 @@
+/**
+ * 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 { ErrorType } from '../../../../basics/error-type';
+import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
+import { NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';
+import { FUNCTION_NAMES_TEXT } from '../../function-names';
+import { Leftb } from '../index';
+
+describe('Test LEFTB function', () => {
+ const leftbFunction = new Leftb(FUNCTION_NAMES_TEXT.LEFTB);
+
+ describe('Leftb', () => {
+ describe('Single Value Tests', () => {
+ it('Should return leftmost bytes of a single text', () => {
+ const text = StringValueObject.create('Hello World');
+ const numBytes = NumberValueObject.create(5);
+ const result = leftbFunction.calculate(text, numBytes);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([['Hello']]);
+ });
+
+ it('Should return full text if byte length exceeds text length', () => {
+ const text = StringValueObject.create('Hello');
+ const numBytes = NumberValueObject.create(10); // Exceeding text length
+ const result = leftbFunction.calculate(text, numBytes);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([['Hello']]);
+ });
+
+ it('Should handle zero byte length correctly', () => {
+ const text = StringValueObject.create('Hello');
+ const numBytes = NumberValueObject.create(0); // Zero byte length
+ const result = leftbFunction.calculate(text, numBytes);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([['']]);
+ });
+
+ it('Should return ErrorType.VALUE for negative byte length', () => {
+ const text = StringValueObject.create('Hello');
+ const numBytes = NumberValueObject.create(-1); // Negative byte length
+ const result = leftbFunction.calculate(text, numBytes);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([[ErrorType.VALUE]]);
+ });
+
+ it('Should handle emojis and byte length correctly', () => {
+ const text = StringValueObject.create('😊Hello');
+ const numBytes = NumberValueObject.create(1); // Bytes needed to capture '😊'
+ const result = leftbFunction.calculate(text, numBytes);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([['😊']]);
+ });
+ });
+
+ it('Extracts characters from array by specifying single numChar', () => {
+ const textArray = new ArrayValueObject({
+ calculateValueList: transformToValueObject([
+ ['Hello'],
+ ['World'],
+ ['New World'],
+ ['Example'],
+ ]),
+ rowCount: 4,
+ columnCount: 1,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const numChars = NumberValueObject.create(3);
+ const result = leftbFunction.calculate(textArray, numChars);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([
+ ['Hel'], // First character of 'Hello'
+ ['Wor'], // First two characters of 'World'
+ ['New'], // First three characters of 'Test'
+ ['Exa'], // First four characters of 'Example'
+ ]);
+ });
+ it('Extracts characters from array', () => {
+ const textArray = new ArrayValueObject({
+ calculateValueList: transformToValueObject([
+ ['Hello'],
+ ['World'],
+ ['Test'],
+ ['Example'],
+ ]),
+ rowCount: 4,
+ columnCount: 1,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const numCharsArray = new ArrayValueObject({
+ calculateValueList: transformToValueObject([
+ [1],
+ [2],
+ [3],
+ [4],
+ ]),
+ rowCount: 4,
+ columnCount: 1,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const result = leftbFunction.calculate(textArray, numCharsArray);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([
+ ['H'], // First character of 'Hello'
+ ['Wo'], // First two characters of 'World'
+ ['Tes'], // First three characters of 'Test'
+ ['Exam'], // First four characters of 'Example'
+ ]);
+ });
+
+ it('Handles numChars not provided for array', () => {
+ const textArray = new ArrayValueObject({
+ calculateValueList: transformToValueObject([
+ ['Hello'],
+ ['World'],
+ ['Test'],
+ ['Example'],
+ ]),
+ rowCount: 4,
+ columnCount: 1,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const result = leftbFunction.calculate(textArray);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([
+ ['H'], // Default to first character of 'Hello'
+ ['W'], // Default to first character of 'World'
+ ['T'], // Default to first character of 'Test'
+ ['E'], // Default to first character of 'Example'
+ ]);
+ });
+ it('Handles extracting from text with emojis', () => {
+ const text = StringValueObject.create('Hello 😊 World');
+ const numChars = NumberValueObject.create(7);
+ const result = leftbFunction.calculate(text, numChars);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([['Hello 😊']]);
+ });
+
+ it('Handles extracting with numChars as zero', () => {
+ const text = StringValueObject.create('Hello');
+ const numChars = NumberValueObject.create(0);
+ const result = leftbFunction.calculate(text, numChars);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([['']]);
+ });
+
+ it('Handles extracting CJK, first byte', () => {
+ const textArray = new ArrayValueObject({
+ calculateValueList: transformToValueObject([
+ ['销售额'],
+ ['から'],
+ ['이트'],
+ ]),
+ rowCount: 3,
+ columnCount: 1,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const result = leftbFunction.calculate(textArray);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([
+ [''],
+ [''],
+ [''],
+ ]);
+ });
+
+ it('Handles extracting CJK, first character', () => {
+ const textArray = new ArrayValueObject({
+ calculateValueList: transformToValueObject([
+ ['销售额'],
+ ['から'],
+ ['이트'],
+ ]),
+ rowCount: 3,
+ columnCount: 1,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const result = leftbFunction.calculate(textArray, NumberValueObject.create(2));
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([
+ ['销'],
+ ['か'],
+ ['이'],
+ ]);
+ });
+ it('Handles extracting multiple languages', () => {
+ const textArray = new ArrayValueObject({
+ calculateValueList: transformToValueObject([
+ ['销售额'],
+ ['uから'],
+ ['이u트'],
+ ['이트u'],
+ ]),
+ rowCount: 4,
+ columnCount: 1,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const result = leftbFunction.calculate(textArray, NumberValueObject.create(3));
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([
+ ['销'],
+ ['uか'],
+ ['이u'],
+ ['이'],
+ ]);
+ });
+ it('Text is array, numBytes is array', () => {
+ const textArray = new ArrayValueObject({
+ calculateValueList: transformToValueObject([
+ [1, ' ', 1.23, true, false, null, 0, '100', '2.34', 'test', -3, ErrorType.NAME],
+ ]),
+ rowCount: 1,
+ columnCount: 12,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const numCharsArray = new ArrayValueObject({
+ calculateValueList: transformToValueObject([
+ [1],
+ [' '],
+ [1.23],
+ [true],
+ [false],
+ [null],
+ [0],
+ ['100'],
+ ['2.34'],
+ ['test'],
+ [-3],
+ [ErrorType.NAME],
+ ]),
+ rowCount: 12,
+ columnCount: 1,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const result = leftbFunction.calculate(textArray, numCharsArray);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([['1', ' ', '1', 'T', 'F', '', '0', '1', '2', 't', '-', ErrorType.NAME], [ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.NAME], ['1', ' ', '1', 'T', 'F', '', '0', '1', '2', 't', '-', ErrorType.NAME], ['1', ' ', '1', 'T', 'F', '', '0', '1', '2', 't', '-', ErrorType.NAME], ['', '', '', '', '', '', '', '', '', '', '', ErrorType.NAME], ['', '', '', '', '', '', '', '', '', '', '', ErrorType.NAME], ['', '', '', '', '', '', '', '', '', '', '', ErrorType.NAME], ['1', ' ', '1.23', 'TRUE', 'FALSE', '', '0', '100', '2.34', 'test', '-3', ErrorType.NAME], ['1', ' ', '1.', 'TR', 'FA', '', '0', '10', '2.', 'te', '-3', ErrorType.NAME], [ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.NAME], [ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.VALUE, ErrorType.NAME], [ErrorType.NAME, ErrorType.NAME, ErrorType.NAME, ErrorType.NAME, ErrorType.NAME, ErrorType.NAME, ErrorType.NAME, ErrorType.NAME, ErrorType.NAME, ErrorType.NAME, ErrorType.NAME, ErrorType.NAME]]);
+ });
+ });
+});
diff --git a/packages/engine-formula/src/functions/text/leftb/index.ts b/packages/engine-formula/src/functions/text/leftb/index.ts
new file mode 100644
index 0000000000..20a3f903bd
--- /dev/null
+++ b/packages/engine-formula/src/functions/text/leftb/index.ts
@@ -0,0 +1,112 @@
+/**
+ * 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 { charLenByte } from '../../../engine/utils/char-kit';
+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';
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
+
+export class Leftb extends BaseFunction {
+ override minParams = 1;
+
+ override maxParams = 2;
+
+ override calculate(text: BaseValueObject, numBytes?: BaseValueObject) {
+ if (text.isError()) {
+ return text;
+ }
+
+ if (numBytes?.isError()) {
+ return numBytes;
+ }
+
+ const _numBytes = numBytes || NumberValueObject.create(1);
+
+ const maxRowLength = Math.max(
+ text.isArray() ? (text as ArrayValueObject).getRowCount() : 1,
+ _numBytes && _numBytes.isArray() ? (_numBytes as ArrayValueObject).getRowCount() : 1
+ );
+
+ const maxColumnLength = Math.max(
+ text.isArray() ? (text as ArrayValueObject).getColumnCount() : 1,
+ _numBytes && _numBytes.isArray() ? (_numBytes as ArrayValueObject).getColumnCount() : 1
+ );
+
+ const textArray = expandArrayValueObject(maxRowLength, maxColumnLength, text);
+ const numBytesArray = expandArrayValueObject(maxRowLength, maxColumnLength, _numBytes);
+
+ return textArray.map((textValue, rowIndex, columnIndex) => {
+ return this._handleSingleText(textValue, rowIndex, columnIndex, numBytesArray);
+ });
+ }
+
+ private _handleSingleText(textValue: BaseValueObject, rowIndex: number, columnIndex: number, numBytesArray: ArrayValueObject) {
+ let numBytes = numBytesArray.get(rowIndex, columnIndex) || NumberValueObject.create(1);
+
+ if (numBytes.isError()) {
+ return numBytes;
+ }
+
+ let textValueString = textValue.getValue();
+
+ if (textValue.isNull()) {
+ textValueString = '';
+ }
+
+ if (textValue.isBoolean()) {
+ textValueString = textValueString ? 'TRUE' : 'FALSE';
+ }
+
+ textValueString = `${textValueString}`;
+
+ if (numBytes.isString() || numBytes.isBoolean() || numBytes.isNull()) {
+ numBytes = numBytes.convertToNumberObjectValue();
+ }
+
+ if (numBytes.isError()) {
+ return numBytes;
+ }
+
+ const numBytesValueNumber = Math.floor(+numBytes.getValue());
+
+ if (numBytesValueNumber < 0) {
+ return ErrorValueObject.create(ErrorType.VALUE);
+ }
+
+ return StringValueObject.create(this._sliceByBytes(textValueString, numBytesValueNumber));
+ }
+
+ private _sliceByBytes(text: string, numBytes: number) {
+ let byteCount = 0;
+ let sliceIndex = 0;
+
+ // Iterate over each Unicode character (correctly handling multi-byte characters and emoji)
+ for (let i = 0; i < text.length; i++) {
+ const char = text[i];
+ const charByteLength = charLenByte(char);
+ if (byteCount + charByteLength > numBytes) {
+ break;
+ }
+ byteCount += charByteLength;
+ sliceIndex++;
+ }
+
+ return [...text].slice(0, sliceIndex).join('');
+ }
+}
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.ts
index 85cc9f6dc5..bfd56f8d1d 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
@@ -235,8 +235,8 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ text: { name: 'text', detail: 'The text string that contains the characters you want to extract.' },
+ numBytes: { name: 'num_bytes', detail: 'Specifies the number of characters you want LEFTB to extract, based on bytes.' },
},
},
LEN: {
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.ts
index f9f687b822..2e77d098d9 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
@@ -236,8 +236,8 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ text: { name: '文字列', detail: '取り出す文字を含む文字列を指定します。' },
+ numBytes: { name: 'バイト数', detail: 'LEFTB で取り出す文字数をバイト数で指定します。' },
},
},
LEN: {
diff --git a/packages/sheets-formula/src/locale/function-list/text/ru-RU.ts b/packages/sheets-formula/src/locale/function-list/text/ru-RU.ts
index c36b6da06b..00fa3eef1e 100644
--- a/packages/sheets-formula/src/locale/function-list/text/ru-RU.ts
+++ b/packages/sheets-formula/src/locale/function-list/text/ru-RU.ts
@@ -235,8 +235,8 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'первый' },
- number2: { name: 'number2', detail: 'второй' },
+ text: { name: 'Текст', detail: 'Текстовая строка, содержащая символы, которые требуется извлечь.' },
+ numBytes: { name: 'Количество_байт', detail: 'Количество символов, извлекаемых функцией ЛЕВБ.' },
},
},
LEN: {
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.ts
index 9bdc5a3e0a..2a74df4209 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
@@ -226,7 +226,7 @@ export default {
},
},
LEFTB: {
- description: '返回文本值中最左边的字符',
+ description: '返回文本值中最左边的字符。',
abstract: '返回文本值中最左边的字符',
links: [
{
@@ -235,8 +235,8 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ text: { name: '文本', detail: '包含要提取的字符的文本字符串。' },
+ numBytes: { name: '字节数', detail: '按字节指定要由 LEFTB 提取的字符的数量。' },
},
},
LEN: {
diff --git a/packages/sheets-formula/src/locale/function-list/text/zh-TW.ts b/packages/sheets-formula/src/locale/function-list/text/zh-TW.ts
index bf7d2e4155..2c8cde1a1b 100644
--- a/packages/sheets-formula/src/locale/function-list/text/zh-TW.ts
+++ b/packages/sheets-formula/src/locale/function-list/text/zh-TW.ts
@@ -235,8 +235,8 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ text: { name: '文字', detail: '內含所要擷取字元的文字字串。' },
+ numBytes: { name: '字元數', detail: '指定 LEFTB 所要擷取的字元數,以位元組為單位。' },
},
},
LEN: {
diff --git a/packages/sheets-formula/src/services/function-list/text.ts b/packages/sheets-formula/src/services/function-list/text.ts
index a23a4a14ae..ff96fae5a3 100644
--- a/packages/sheets-formula/src/services/function-list/text.ts
+++ b/packages/sheets-formula/src/services/function-list/text.ts
@@ -354,17 +354,17 @@ export const FUNCTION_LIST_TEXT: IFunctionInfo[] = [
abstract: 'formula.functionList.LEFTB.abstract',
functionParameter: [
{
- name: 'formula.functionList.LEFTB.functionParameter.number1.name',
- detail: 'formula.functionList.LEFTB.functionParameter.number1.detail',
- example: 'A1:A20',
+ name: 'formula.functionList.LEFTB.functionParameter.text.name',
+ detail: 'formula.functionList.LEFTB.functionParameter.text.detail',
+ example: '"Hello Univer"',
require: 1,
repeat: 0,
},
{
- name: 'formula.functionList.LEFTB.functionParameter.number2.name',
- detail: 'formula.functionList.LEFTB.functionParameter.number2.detail',
- example: 'A1:A20',
- require: 1,
+ name: 'formula.functionList.LEFTB.functionParameter.numBytes.name',
+ detail: 'formula.functionList.LEFTB.functionParameter.numBytes.detail',
+ example: '1',
+ require: 0,
repeat: 0,
},
],