core/validators/link.validator.ts

core/validators/link.validator.ts is a file in Bane's Lab Content. 30 lines of code and 9 definitions.

import type { LinkChange, LinkChanges, LinkSet, PageSection } from "#types/writing.types";

const pageLinks = function pageLinks(sections: readonly PageSection[]): ReadonlyMap<string, ReadonlySet<string>> {
    const byPage = new Map<string, Set<string>>();
    for (const section of sections) {
        const held = byPage.get(section.page) ?? new Set<string>();
        for (const link of section.links) {
            held.add(link);
        }
        byPage.set(section.page, held);
    }
    return byPage;
};

export const linkChanges = function linkChanges(baseline: LinkSet, sections: readonly PageSection[]): LinkChanges {
    const bySection = new Map(sections.map((section) => [section.key, new Set(section.links)]));
    const pageOf = new Map(sections.map((section) => [section.key, section.page]));
    const byPage = pageLinks(sections);
    const lost: LinkChange[] = [];
    const moved: LinkChange[] = [];
    for (const [key, links] of Object.entries(baseline)) {
        const held = bySection.get(key);
        const onPage = byPage.get(pageOf.get(key) ?? key);
        for (const target of links ?? []) {
            if (held?.has(target) === true) {
                continue;
            }
            (onPage?.has(target) === true ? moved : lost).push({ key, target });
        }
    }
    return { lost, moved };
};