UNPKG

eslint-plugin-import-sorting

Version:

ESLint plugin to group and sort imports by module, à la Python isort

49 lines (48 loc) 1.64 kB
"use strict"; Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); function compare(a, b, options) { var _a, _b; if (a.group === "unassigned" || b.group === "unassigned") return 0; if ((_a = b.dependencies) == null ? void 0 : _a.includes(a.name)) return -1; if ((_b = a.dependencies) == null ? void 0 : _b.includes(b.name)) return 1; let orderCoefficient = options.order === "asc" ? 1 : -1; let sortingFunction; let nodeValueGetter = options.nodeValueGetter ?? ((node) => node.name); sortingFunction = (aNode, bNode) => { let aImport = stripProtocol(nodeValueGetter(aNode)); let bImport = stripProtocol(nodeValueGetter(bNode)); if (aImport.startsWith(".") && bImport.startsWith(".")) { return compareDotSegments(aImport, bImport); } return compareString(aImport, bImport); }; return orderCoefficient * sortingFunction(a, b); } function stripProtocol(name) { return name.replace(/^(node|bun):/, ""); } function compareString(first, second) { if (first.startsWith(".") && !second.startsWith(".")) return 1; if (!first.startsWith(".") && second.startsWith(".")) return -1; return first.localeCompare(second, "en", { caseFirst: "upper", numeric: true, sensitivity: "case" }); } function compareDotSegments(first, second) { let regex = /\.+(?=\/)/g; let firstCount = (first.match(regex) ?? []).join("").length; let secondCount = (second.match(regex) ?? []).join("").length; if (secondCount < firstCount) return -1; if (firstCount < secondCount) return 1; return compareString(first, second); } exports.compare = compare;