Files
NewTube/server/suggest.mjs
T

42 lines
1.4 KiB
JavaScript

// Suggest helpers (pure, no network, no DB) — shared dedup policy:
// the same occurrence is only ever returned once (first provider wins).
/** Normalize a suggestion string for dedup comparisons. */
export function normSuggestKey(s) {
return String(s ?? '').trim().toLowerCase().replace(/\s+/g, ' ');
}
/**
* Deduplicate suggestion groups across providers: the same occurrence
* (case/whitespace-insensitive) is kept only once, in the first provider
* group (registry order). Within a group, order is preserved (first wins).
* @param {Record<string, string[]>} groups
* @param {string[]} order provider ids in priority order
* @returns {Record<string, string[]>} same keys, deduped lists
*/
export function dedupeSuggestGroups(groups, order = ['yt', 'dm', 'tw', 'pt', 'od', 'ru']) {
const src = groups && typeof groups === 'object' ? groups : {};
const seen = new Set();
const out = {};
const pushList = (pid) => {
const list = Array.isArray(src[pid]) ? src[pid] : [];
const clean = [];
for (const raw of list) {
const t = String(raw ?? '').trim();
if (!t) continue;
const k = normSuggestKey(t);
if (seen.has(k)) continue;
seen.add(k);
clean.push(t);
}
out[pid] = clean;
};
for (const pid of order) {
if (Object.prototype.hasOwnProperty.call(src, pid)) pushList(pid);
}
for (const pid of Object.keys(src)) {
if (!order.includes(pid)) pushList(pid);
}
return out;
}