feat(web): collator sort helpers + ExternalUriLink + filter/uri i18n (#50)
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import { byKey, byLabel, compareStrings } from "./sort";
|
||||
|
||||
const L = (label: string) => ({ labels: [{ lang: "en", label }] });
|
||||
|
||||
test("byLabel sorts case-insensitively and locale-aware", () => {
|
||||
const sorted = [L("Iron"), L("bronze"), L("Amber")].sort(byLabel("en")).map((x) => x.labels[0].label);
|
||||
|
||||
expect(sorted).toEqual(["Amber", "bronze", "Iron"]);
|
||||
});
|
||||
|
||||
test("byKey sorts keys with numeric awareness", () => {
|
||||
const sorted = [{ key: "item10" }, { key: "item2" }, { key: "item1" }].sort(byKey("en")).map((x) => x.key);
|
||||
|
||||
expect(sorted).toEqual(["item1", "item2", "item10"]);
|
||||
});
|
||||
|
||||
test("compareStrings is case-insensitive", () => {
|
||||
expect(compareStrings("en", "bronze", "BRONZE")).toBe(0);
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { components } from "../api/schema";
|
||||
|
||||
import { labelText } from "./labels";
|
||||
|
||||
type LabelView = components["schemas"]["LabelView"];
|
||||
|
||||
const collators = new Map<string, Intl.Collator>();
|
||||
|
||||
function collatorFor(lang: string): Intl.Collator {
|
||||
let c = collators.get(lang);
|
||||
|
||||
if (!c) {
|
||||
c = new Intl.Collator(lang, { sensitivity: "base", numeric: true });
|
||||
collators.set(lang, c);
|
||||
}
|
||||
|
||||
return c;
|
||||
}
|
||||
|
||||
export function compareStrings(lang: string, a: string, b: string): number {
|
||||
return collatorFor(lang).compare(a, b);
|
||||
}
|
||||
|
||||
export function byLabel(lang: string) {
|
||||
return (a: { labels: LabelView[] }, b: { labels: LabelView[] }) =>
|
||||
compareStrings(lang, labelText(a.labels, lang), labelText(b.labels, lang));
|
||||
}
|
||||
|
||||
export function byKey(lang: string) {
|
||||
return (a: { key: string }, b: { key: string }) => compareStrings(lang, a.key, b.key);
|
||||
}
|
||||
Reference in New Issue
Block a user