Add utility functions and unit tests

This commit is contained in:
Franziska Richter 2026-03-03 09:30:00 +00:00
parent f034851a1f
commit d89a0f7c4e
2 changed files with 29 additions and 0 deletions

17
src/utils/format.ts Normal file
View file

@ -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]}`;
}

12
tests/format.test.ts Normal file
View file

@ -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'));
});