diff --git a/scripts/reorder-search-index.mjs b/scripts/reorder-search-index.mjs index 593ab7a83c72..291c9628863c 100644 --- a/scripts/reorder-search-index.mjs +++ b/scripts/reorder-search-index.mjs @@ -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"); }