From 8a2946687b1886f8fd12c64d2013558d63016972 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Felix=20B=C3=B6hm?= <188768+fb55@users.noreply.github.com> Date: Sun, 26 Dec 2021 14:45:46 +0100 Subject: [PATCH] refactor(stringify): Simplify selectors --- src/stringify.ts | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/src/stringify.ts b/src/stringify.ts index 68929e18..4f809f8a 100644 --- a/src/stringify.ts +++ b/src/stringify.ts @@ -34,27 +34,36 @@ const charsToEscapeInName = new Set( */ export function stringify(selector: Selector[][]): string { return selector - .map((token) => token.map((t) => stringifyToken(t)).join("")) + .map((token) => token.map(stringifyToken).join("")) .join(", "); } -function stringifyToken(token: Selector): string { +function stringifyToken( + token: Selector, + index: number, + arr: Selector[] +): string { switch (token.type) { // Simple types case SelectorType.Child: - return " > "; + return index === 0 ? "> " : " > "; case SelectorType.Parent: - return " < "; + return index === 0 ? "< " : " < "; case SelectorType.Sibling: - return " ~ "; + return index === 0 ? "~ " : " ~ "; case SelectorType.Adjacent: - return " + "; + return index === 0 ? "+ " : " + "; case SelectorType.Descendant: return " "; case SelectorType.ColumnCombinator: - return " || "; + return index === 0 ? "|| " : " || "; case SelectorType.Universal: - return `${getNamespace(token.namespace)}*`; + // Return an empty string if the selector isn't needed. + return token.namespace === "*" && + index + 1 < arr.length && + "name" in arr[index + 1] + ? "" + : `${getNamespace(token.namespace)}*`; case SelectorType.Tag: return getNamespacedName(token);