import { readFileSync, readdirSync, statSync } from 'node:fs'; import { dirname, join, relative } from 'node:path'; import { fileURLToPath } from 'node:url'; import { describe, expect, test } from 'vitest'; import { plural } from './plural.js'; describe('plural', () => { test('says a count with the noun that agrees with it', () => { expect(plural(1, 'track', 'tracks')).toBe('1 track'); expect(plural(0, 'track', 'tracks')).toBe('0 tracks'); expect(plural(2, 'album has', 'albums have')).toBe('2 albums have'); expect(plural(26_171, 'track', 'tracks')).toBe('26,171 tracks'); }); }); // One way to say a count, so every count agrees on wording and the // thousands separator. A hand-written copy has a tell this guard looks for: // - a branch that spells the one: `n === 1 ? '1 track' : ...`; // - the number beside a choice of noun: `{n} {n === 1 ? ...}` in markup, // or `${n} ${n === 1 ? ...}` in a template string; // - the suffix trick: `minute${n === 1 ? '' : 's'}`. // A choice of words with no count in it ("it" / "they", "yesterday") is // not a count label and stays a ternary. const SRC = join(dirname(fileURLToPath(import.meta.url)), '../..'); const HAND_ROLLED = [ /=== 1 \? ['"`]1 /, /\{([\w.]+)\}\s*\{\1 === 1 \?/, /\$\{([\w.]+)\} \$\{\1 === 1 \?/, /=== 1 \? '' : 's'/ ]; /** Comments describe the forbidden shape; strip them before asserting its absence. */ const stripComments = (s: string) => s.replace(//g, '').replace(/^\s*\/\/.*$/gm, ''); function sources(dir: string): string[] { return readdirSync(dir).flatMap((name) => { const path = join(dir, name); if (statSync(path).isDirectory()) return sources(path); return /\.(svelte|ts)$/.test(name) && !/\.test\.ts$/.test(name) ? [path] : []; }); } describe('count labels', () => { test('every count in the web app is said by plural()', () => { const offenders = sources(SRC).flatMap((path) => { const text = stripComments(readFileSync(path, 'utf8')); return HAND_ROLLED.some((re) => re.test(text)) ? [relative(SRC, path)] : []; }); expect(offenders).toEqual([]); }); });