diff --git a/package.json b/package.json index 389dae2..c596aec 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@risc0/ui", - "version": "0.0.30", + "version": "0.0.31", "sideEffects": false, "type": "module", "scripts": { diff --git a/utils/truncate.spec.ts b/utils/truncate.spec.ts new file mode 100644 index 0000000..7375cd7 --- /dev/null +++ b/utils/truncate.spec.ts @@ -0,0 +1,52 @@ +import truncate from './truncate'; + +describe('truncate', () => { + it('should truncate longer textes with a fixed length of characters in the last chunk', () => { + const text = '1234567890abcdefghijklmnopqrstuvwxyz'; + const chars = 14; + const result = truncate(text, chars); + expect(result).toBe('1234567890…wxyz'); + }); + + it('should truncate the text when the chars parameter is less than the length of the text', () => { + const text = '1234567890'; + const chars = 5; + const result = truncate(text, chars); + expect(result).toBe('123…90'); + }); + + it('should return the full text when the chars parameter is equal to the length of the text', () => { + const text = '1234567890'; + const chars = 10; + const result = truncate(text, chars); + expect(result).toBe(text); + }); + + it('should return the full text when the chars parameter is greater than the length of the text', () => { + const text = '1234567890'; + const chars = 11; + const result = truncate(text, chars); + expect(result).toBe(text); + }); + + it('should handle an text with an odd number of characters', () => { + const text = '123456789'; + const chars = 5; + const result = truncate(text, chars); + expect(result).toBe('123…89'); + }); + + it('should handle an text with only one character', () => { + const text = '1'; + const chars = 1; + const result = truncate(text, chars); + expect(result).toBe(text); + }); + + it('should handle an empty text', () => { + const text = ''; + const chars = 1; + const result = truncate(text, chars); + expect(result).toBe(text); + }); +}); diff --git a/utils/truncate.ts b/utils/truncate.ts new file mode 100644 index 0000000..0c044e2 --- /dev/null +++ b/utils/truncate.ts @@ -0,0 +1,22 @@ +const MAX_LAST_CHUNK_LENGTH = 4; + +const truncate = (text: string, chars = 9): string => { + if (chars >= text.length) { + return text; + } + + if (chars < MAX_LAST_CHUNK_LENGTH * 2) { + const firstChunk = text.slice(0, Math.max(0, Math.round(chars / 2))); + const lastChunk = text.slice(-Math.floor(chars / 2)); + + return `${firstChunk}…${lastChunk}`; + } + + const firstChunk = text.slice(0, Math.max(0, chars - MAX_LAST_CHUNK_LENGTH)); + + const lastChunk = text.substr(text.length - MAX_LAST_CHUNK_LENGTH, chars); + + return `${firstChunk}…${lastChunk}`; +}; + +export default truncate;