Skip to content

Commit

Permalink
Trim redundant empty array elements
Browse files Browse the repository at this point in the history
If a value is assigned to an array later, there’s no need to keep empty
array items at the end.
  • Loading branch information
remcohaszing committed Apr 6, 2024
1 parent bc3b11b commit 16768f5
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
2 changes: 1 addition & 1 deletion fixtures/array-recursive-nested/input.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Used as input
// { preserveReferences: true }
export default (() => {
const $1 = ['variable 1', ,],
const $1 = ['variable 1'],
$0 = ['variable 0', $1]
return ($1[1] = $0)
})()
Expand Down
8 changes: 8 additions & 0 deletions src/estree-util-value-to-estree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -412,10 +412,12 @@ export function valueToEstree(value: unknown, options: Options = {}): Expression

if (Array.isArray(val)) {
const elements: (Expression | null)[] = Array.from({ length: val.length })
let trimmable: number | undefined

for (let index = 0; index < val.length; index += 1) {
if (!(index in val)) {
elements[index] = null
trimmable = undefined
continue
}

Expand All @@ -427,6 +429,7 @@ export function valueToEstree(value: unknown, options: Options = {}): Expression
namedContexts.indexOf(childContext) >= namedContexts.indexOf(context)
) {
elements[index] = null
trimmable ||= index
addFinalizer(child, {
type: 'AssignmentExpression',
operator: '=',
Expand All @@ -441,9 +444,14 @@ export function valueToEstree(value: unknown, options: Options = {}): Expression
})
} else {
elements[index] = generate(child)
trimmable = undefined
}
}

if (trimmable != null) {
elements.splice(trimmable)
}

return {
type: 'ArrayExpression',
elements
Expand Down

0 comments on commit 16768f5

Please sign in to comment.