eslint-plugin-unicorn
eslint-plugin-unicorn copied to clipboard
Rule proposal: prefer-direct-value-assignment
Description
I have stumbled upon code a couple of times that first assigns an array and then pushes values unconditionally. That is not ideal, since it requires the array to potentially resize right away and change its internal shape, while also making it less readable and more verbose. Instead, just assign the values directly. The same applies to objects with properties.
Examples
// ❌
const foo = {}
foo.array = []
const random = Math.random()
foo.array.push(42)
// ✅
const foo = {
array: [42]
}
const random = Math.random()
Proposed rule name
prefer-direct-value-assignment prefer-concise-values
Additional Info
No response
An immediate update makes sense to apply.
// ❌
const foo = {}
foo.array = []
// ✅
const foo = {
array: []
}
But after another call doesn't, it's hard to know what's done there.
This got superseded by https://github.com/sindresorhus/eslint-plugin-unicorn/issues/2775
Sorry that I forgot about this one when I open #2775