diff --git a/src/utils/format.ts b/src/utils/format.ts new file mode 100644 index 0000000..e6b1e58 --- /dev/null +++ b/src/utils/format.ts @@ -0,0 +1,17 @@ +export function formatDate(iso: string): string { + return new Intl.DateTimeFormat('de-DE', { + day: '2-digit', month: '2-digit', year: 'numeric', + }).format(new Date(iso)); +} + +export function truncate(str: string, maxLen: number): string { + return str.length <= maxLen ? str : str.slice(0, maxLen - 1) + '…'; +} + +export function bytesToHuman(bytes: number): string { + const units = ['B', 'KB', 'MB', 'GB']; + let n = bytes; + let i = 0; + while (n >= 1024 && i < units.length - 1) { n /= 1024; i++; } + return `${n.toFixed(1)} ${units[i]}`; +} diff --git a/tests/format.test.ts b/tests/format.test.ts new file mode 100644 index 0000000..0e1b208 --- /dev/null +++ b/tests/format.test.ts @@ -0,0 +1,12 @@ +import { describe, it, expect } from 'vitest'; +import { truncate, bytesToHuman } from '../src/utils/format'; + +describe('truncate', () => { + it('leaves short strings alone', () => expect(truncate('hi', 10)).toBe('hi')); + it('truncates long strings', () => expect(truncate('hello world', 7)).toBe('hello w…')); +}); + +describe('bytesToHuman', () => { + it('formats bytes', () => expect(bytesToHuman(1024)).toBe('1.0 KB')); + it('formats megabytes', () => expect(bytesToHuman(1536 * 1024)).toBe('1.5 GB')); +});