Files
booksorter/src/shared/cutter.ts
T

63 lines
2.5 KiB
TypeScript

// LC cutter table. Digits for a letter: the entry's own digit, else the lower entry's,
// else (before the first entry) the first entry's.
const VOWEL: Record<string, number> = {
a: 2, b: 2, c: 2, d: 3, e: 3, f: 3, g: 3, h: 3, i: 3, j: 3, k: 3, l: 4, m: 4, n: 5,
o: 5, p: 6, q: 6, r: 7, s: 8, t: 8, u: 9, v: 9, w: 9, x: 9, y: 9, z: 9,
};
const S_TABLE: Record<string, number> = {
a: 2, b: 2, c: 2, d: 3, e: 4, f: 4, g: 4, h: 5, i: 5, j: 5, k: 5, l: 5, m: 6, n: 6,
o: 6, p: 6, q: 6, r: 6, s: 6, t: 7, u: 8, v: 8, w: 9, x: 9, y: 9, z: 9,
};
const QU_TABLE: Record<string, number> = {
a: 3, b: 3, c: 3, d: 3, e: 4, f: 4, g: 4, h: 4, i: 5, j: 5, k: 5, l: 5, m: 5, n: 5,
o: 6, p: 6, q: 6, r: 7, s: 7, t: 8, u: 8, v: 8, w: 8, x: 8, y: 9, z: 9,
};
const CONSONANT: Record<string, number> = {
a: 3, b: 3, c: 3, d: 3, e: 4, f: 4, g: 4, h: 4, i: 5, j: 5, k: 5, l: 5, m: 5, n: 5,
o: 6, p: 6, q: 6, r: 7, s: 7, t: 7, u: 8, v: 8, w: 8, x: 8, y: 9, z: 9,
};
const THIRD: Record<string, number> = {
a: 3, b: 3, c: 3, d: 3, e: 4, f: 4, g: 4, h: 4, i: 5, j: 5, k: 5, l: 5, m: 6, n: 6,
o: 6, p: 7, q: 7, r: 7, s: 7, t: 8, u: 8, v: 8, w: 9, x: 9, y: 9, z: 9,
};
export function cutterFor(name: string): string {
const trimmed = name.trim();
const w = trimmed.normalize('NFD').replace(/[̀-ͯ]/g, '').toUpperCase().replace(/[^A-Z]/g, '').toLowerCase();
if (w === '' || /^\d/.test(trimmed)) return 'A12';
const first = w[0]!;
let table: Record<string, number>;
let rest: string;
let second: number | null;
if ('aeiou'.includes(first)) {
table = VOWEL; rest = w.slice(1);
second = rest ? table[rest[0]!]! : null;
rest = rest.slice(1);
} else if (first === 's') {
rest = w.slice(1);
if (rest.startsWith('ch')) { second = 3; rest = rest.slice(2); }
else { second = rest ? S_TABLE[rest[0]!]! : null; rest = rest.slice(1); }
} else if (first === 'q' && w[1] === 'u') {
rest = w.slice(2);
second = rest ? QU_TABLE[rest[0]!]! : null;
rest = rest.slice(1);
} else {
rest = w.slice(1);
second = rest ? CONSONANT[rest[0]!]! : null;
rest = rest.slice(1);
}
let out = first.toUpperCase() + String(second ?? 2);
if (second !== null && rest) out += String(THIRD[rest[0]!]!);
return out;
}
export function mainEntry(authors: string[], title: string): string {
const a = authors[0]?.trim();
if (a) {
if (a.includes(',')) return a.split(',')[0]!.trim();
const words = a.split(/\s+/);
return words[words.length - 1]!;
}
return title.trim().replace(/^(a|an|the)\s+/i, '');
}