eslint-plugin-beautiful-sort
Version:
eslint plugin for imports sort by their type
106 lines • 3.34 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ImportNode = void 0;
const type_enum_1 = require("./type.enum");
const DEFAULT_AST_TYPE = 'ImportDefaultSpecifier';
const OBJ_AST_TYPE = 'ImportSpecifier';
const NAMESPACE_AST_TYPE = 'ImportNamespaceSpecifier';
class ImportNode {
node;
params;
type = null;
constructor(node, params) {
this.node = node;
this.params = params;
this.type = this.calculateType();
}
getSpecialNumber(target) {
return this.params.special.findIndex((regexp) => {
return regexp.test(target.getImportPath());
});
}
specialCompare(target) {
return this.getSpecialNumber(this) - this.getSpecialNumber(target);
}
getSortTableNumber(target) {
const { sortTable } = this.params;
const type = target.getType() ?? 'rest';
return sortTable[type] ?? sortTable.rest;
}
sortTableCompare(target) {
return this.getSortTableNumber(this) - this.getSortTableNumber(target);
}
isSpecialNode(target) {
return target.getType() === type_enum_1.Type.special;
}
compare(target) {
if (this.isSpecialNode(this) && this.isSpecialNode(target)) {
return this.specialCompare(target);
}
return this.sortTableCompare(target);
}
getNode() {
return this.node;
}
getImportPath() {
return this.node.source.value;
}
getType() {
return this.type;
}
calculateType() {
switch (true) {
case this.isSpecial():
return type_enum_1.Type.special;
case this.isDefault():
return type_enum_1.Type.default;
case this.isDefaultObj():
return type_enum_1.Type.defaultObj;
case this.isObj():
return type_enum_1.Type.obj;
case this.isNamespace():
return type_enum_1.Type.namespace;
case this.isNone():
return type_enum_1.Type.none;
default:
return null;
}
}
isSpecial() {
const { node, params } = this;
const { special } = params;
return special.some((regexp) => regexp.test(node.source.value));
}
isDefault() {
const { specifiers } = this.node;
if (!specifiers.length)
return false;
if (specifiers.length > 1)
return false;
return specifiers[0].type === DEFAULT_AST_TYPE;
}
isDefaultObj() {
const { specifiers } = this.node;
if (specifiers.length < 2)
return false;
const isFirstDefault = specifiers[0].type === DEFAULT_AST_TYPE;
const isSecondObj = specifiers[1].type === OBJ_AST_TYPE;
return isFirstDefault && isSecondObj;
}
isObj() {
const { specifiers } = this.node;
if (!specifiers.length)
return false;
return specifiers[0].type === OBJ_AST_TYPE;
}
isNone() {
return this.node.specifiers.length === 0;
}
isNamespace() {
if (!this.node.specifiers.length)
return false;
return this.node.specifiers[0].type === NAMESPACE_AST_TYPE;
}
}
exports.ImportNode = ImportNode;
//# sourceMappingURL=import-node.js.map