Skip to content

Commit

Permalink
refactor: simplify
Browse files Browse the repository at this point in the history
  • Loading branch information
axelrindle committed Dec 7, 2024
1 parent 58c97dd commit 6cc4ec1
Showing 1 changed file with 1 addition and 46 deletions.
Original file line number Diff line number Diff line change
@@ -1,28 +1,5 @@
import type { Rule } from 'eslint'
import { enforceConfig, jsonSchema } from './config.js'
import { inspect } from 'node:util'

/**
* Groups an array of elements by keys extracted using a specified function.
*
* @param array - The array of elements to be grouped.
* @param keyExtractor - A function that takes an element and returns the key to group by.
* @returns An object with keys being the unique values returned by the keyExtractor and values being arrays of corresponding elements.
*/
function groupBy<T, R extends keyof any>(array: T[], keyExtractor: (item: T) => R) {
const initial: Record<R, T[]> = {} as Record<R, T[]>

return array.reduce((result, current) => {
const key = keyExtractor(current)

if (!result[key]) {
result[key] = []
}

result[key].push(current)
return result
}, initial)
}

const plugin: Rule.RuleModule = {
meta: {
Expand Down Expand Up @@ -53,35 +30,13 @@ const plugin: Rule.RuleModule = {
}

const identifiers = node.specifiers.filter(s => s.type === 'ImportSpecifier')
const identifiersPerLine = groupBy(identifiers, i => {
if (!i.loc) {
throw new Error()
}

return i.loc.start.line
})
console.log(inspect(Object.entries(identifiersPerLine).map(([line, specs]) => [
line,
specs.map(s => ({ name: s.imported.name, loc: s.imported.loc, range: s.imported.range })),
]), false, null))

const identifierNames = identifiers
.sort((a, b) => a.imported.name.localeCompare(b.imported.name))
.map(s => `\t${s.imported.name}`)
const replaced = ['import {', identifierNames.join(',\n'), `} from ${node.source.raw}`].join('\n')

const length = node.loc.end.column - node.loc.start.column
if (identifiers.length > config.maxItems) {
context.report({
node,
messageId: 'mustSplitMany',
data: {
maxItems: config.maxItems.toString(),
},
fix: fixer => fixer.replaceText(node, replaced),
})
}
else if (length > config.maxLineLength) {
if (length > config.maxLineLength) {
context.report({
node,
messageId: 'mustSplitLong',
Expand Down

0 comments on commit 6cc4ec1

Please sign in to comment.