Skip to content

Commit

Permalink
feat: add truncate utils
Browse files Browse the repository at this point in the history
  • Loading branch information
nahoc committed Apr 3, 2024
1 parent a86c2c2 commit fdbf726
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@risc0/ui",
"version": "0.0.30",
"version": "0.0.31",
"sideEffects": false,
"type": "module",
"scripts": {
Expand Down
52 changes: 52 additions & 0 deletions utils/truncate.spec.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
22 changes: 22 additions & 0 deletions utils/truncate.ts
Original file line number Diff line number Diff line change
@@ -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;

0 comments on commit fdbf726

Please sign in to comment.