perfect-postcode/frontend/src/lib/format.test.ts

43 lines
1.6 KiB
TypeScript

import { describe, expect, it } from 'vitest';
import {
buildPercentileScale,
calculateHistogramMean,
formatFilterValue,
formatTransactionDate,
parseInputValue,
roundedPercentages,
} from './format';
describe('format utilities', () => {
it('formats compact filter values and transaction dates', () => {
expect(formatFilterValue(1250)).toBe('1.3k');
expect(formatFilterValue(1_250_000)).toBe('1.3M');
expect(formatFilterValue(1250, true)).toBe('1250');
expect(formatFilterValue(87.4, { raw: true, suffix: '%' })).toBe('87%');
expect(formatTransactionDate(2024.5)).toBe('Jul 2024');
});
it('parses user-entered compact numeric values', () => {
expect(parseInputValue('£1.25M', { prefix: '£', step: 5000 })).toBe(1_250_000);
expect(parseInputValue('45 sqm', { suffix: ' sqm' })).toBe(45);
expect(parseInputValue('2.5万')).toBe(25_000);
expect(parseInputValue('not a number')).toBeNull();
});
it('rounds percentages so displayed values sum to 100', () => {
expect(roundedPercentages([1, 1, 1], 3)).toEqual([34, 33, 33]);
expect(roundedPercentages([1, 2, 3], 6, 1)).toEqual([16.7, 33.3, 50]);
expect(roundedPercentages([5, 5], 0)).toEqual([0, 0]);
});
it('maps histogram percentiles and weighted means consistently', () => {
const histogram = { min: 0, p1: 10, p99: 90, max: 100, counts: [10, 80, 10] };
const scale = buildPercentileScale(histogram);
expect(scale.toValue(0)).toBe(0);
expect(scale.toValue(50)).toBeCloseTo(50);
expect(scale.toPercentile(50)).toBeCloseTo(50);
expect(calculateHistogramMean(histogram)).toBeCloseTo(50);
});
});