From 72d752134f60fe80d4f929ea3c2c5997787de1d4 Mon Sep 17 00:00:00 2001 From: kim Date: Fri, 26 Apr 2024 11:56:42 +0200 Subject: [PATCH] feat: add applyEllipsisOnLength --- src/index.ts | 5 +++++ src/string/string.test.ts | 18 ++++++++++++++++++ src/string/string.ts | 14 ++++++++++++++ 3 files changed, 37 insertions(+) create mode 100644 src/string/string.test.ts create mode 100644 src/string/string.ts diff --git a/src/index.ts b/src/index.ts index 3d0e8581..f5e09d52 100644 --- a/src/index.ts +++ b/src/index.ts @@ -286,3 +286,8 @@ export { type ChatBotMessage, GPTVersion, } from './chatbot/chatbot.js'; + +/** + * string utils + */ +export * from './string/string.js'; diff --git a/src/string/string.test.ts b/src/string/string.test.ts new file mode 100644 index 00000000..08f89411 --- /dev/null +++ b/src/string/string.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest'; + +import { applyEllipsisOnLength } from './string.js'; + +describe('applyEllipsisOnLength', () => { + it('does not add ellipsis', () => { + expect(applyEllipsisOnLength('mystring', 100)).toEqual('mystring'); + expect(applyEllipsisOnLength('my very long string is here', 100)).toEqual( + 'my very long string is here', + ); + }); + it('add ellipsis', () => { + expect(applyEllipsisOnLength('mystring', 2)).toEqual('my…'); + expect(applyEllipsisOnLength('my very long string is here', 10)).toEqual( + 'my very lo…', + ); + }); +}); diff --git a/src/string/string.ts b/src/string/string.ts new file mode 100644 index 00000000..641ee951 --- /dev/null +++ b/src/string/string.ts @@ -0,0 +1,14 @@ +/** + * add ellipsis on string given length + * warning: use css instead of this function if possible + * @param {any} longString:string + * @param {any} maxLength:number + * @returns {any} + */ +export const applyEllipsisOnLength = ( + longString: string, + maxLength: number, +): string => + `${longString.slice(0, maxLength)}${ + (longString.length || 0) > maxLength ? '…' : '' + }`;