Skip to content

Latest commit

 

History

History
111 lines (72 loc) · 2.68 KB

prefer-spread.md

File metadata and controls

111 lines (72 loc) · 2.68 KB

Prefer the spread operator over Array.from(…), Array#concat(…), Array#{slice,toSpliced}() and String#split('')

💼 This rule is enabled in the ✅ recommended config.

🔧💡 This rule is automatically fixable by the --fix CLI option and manually fixable by editor suggestions.

Enforces the use of the spread operator (...) over outdated patterns. This also helps keep consistency by using a single flexible operator instead of:

  • Array.from(…)

    Convert Iterable to Array.

    This rule adds on to the built-in prefer-spread rule, which only flags uses of .apply(). Does not enforce for TypedArray.from().

  • Array#concat(…)

    Concat an Array with one or more Array's or Array elements.

  • Array#slice()

    Shallow copy an Array.

    Variables named arrayBuffer, blob, buffer, file, and this are ignored.

  • Array#toSpliced()

    Shallow copy an Array.

  • String#split('')

    Split a string into an array of characters.

    Note: The suggestion fix may get different result.

To enforce the spread operator over Object#assign(), use the built-in prefer-object-spread rule.

Fail

Array.from(set).map(element => foo(element));
const array = array1.concat(array2);
const copy = array.slice();
const copy = array.slice(0);
const copy = array.toSpliced();
const characters = string.split('');

Pass

[...set].map(element => foo(element));
const array = [...array1, ...array2];
const tail = array.slice(1);
const copy = [...array];
const characters = [...string];

With the unicorn/no-useless-spread rule

Some cases are fixed using extra spread syntax. Therefore we recommend enabling the unicorn/no-useless-spread rule to fix it.

For example:

const baz = [2];
call(foo, ...[bar].concat(baz));

Will be fixed to:

const baz = [2];
call(foo, ...[bar, ...baz]);

unicorn/no-useless-spread will fix it to:

const baz = [2];
call(foo, bar, ...baz);