Skip to content

Commit

Permalink
enhance performance and remove en-us fallback
Browse files Browse the repository at this point in the history
  • Loading branch information
fiji-flo committed Dec 17, 2024
1 parent aec80a6 commit 27f5819
Showing 1 changed file with 14 additions and 21 deletions.
35 changes: 14 additions & 21 deletions scripts/reorder-search-index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,26 @@ async function main() {
const [refPath, inputPath, outputPath = null] = process.argv.slice(2);

const readJson = (path) => JSON.parse(readFileSync(path, "utf-8"));
const getSlug = ({ url }) => url.replace(/^\/[^/]+\/docs\//, "");
const slugify = (url) => url.replace(/^\/[^/]+\/docs\//, "");

// Read reference (e.g. "client/build/en-us/search-index.json").
const ref = readJson(refPath);
const refSlugs = ref.map(getSlug);
// Read reference (e.g. "client/build/en-us/search-index.json")
// into map: slug -> index-in-ref
const ref = Object.fromEntries(
readJson(refPath).map(({ url }, i) => [slugify(url), i])
);

// Read index (e.g. "client/build/de/search-index.json").
const input = readJson(inputPath);
const inputSlugs = input.map(getSlug);

const result = [];
// Array of tuples (index-in-ref, input-entry).
const indexed = input.map(({ title, url }) => [
ref[slugify(url)] ?? Infinity,
{ title, url },
]);
// Sort by index-in-ref.
indexed.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));

// Add entry for each reference item.
for (const [refIndex, slug] of refSlugs.entries()) {
const inputIndex = inputSlugs.indexOf(slug);
// Use reference item if it's currently missing in index.
const item = inputIndex !== -1 ? input[inputIndex] : ref[refIndex];
result.push(item);
}

// Add entry for any item that is NOT in the reference (e.g. moved/removed).
for (const [inputIndex, slug] of inputSlugs.entries()) {
if (!refSlugs.includes(slug)) {
const item = input[inputIndex];
result.push(item);
}
}
const result = indexed.map(([, entry]) => entry);

writeFileSync(outputPath ?? inputPath, JSON.stringify(result), "utf-8");
}
Expand Down

0 comments on commit 27f5819

Please sign in to comment.