### Prefer padStart() over manual string padding with slice (start) Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-string-pad-start-end.js.md This example illustrates manual string padding at the start using `repeat()` followed by `slice()`. The rule suggests simplifying this to `String#padStart()`. ```javascript const foo = ("*".repeat(10) + bar).slice(-10); ``` -------------------------------- ### Class Constructor Parameter with 'get' Prefix Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-non-function-verb-prefix.js.md This example demonstrates a class constructor parameter `getName` with a 'get' prefix, which is not a function. The rule identifies this as a violation. ```javascript class Person { constructor(public getName: string) {} } ``` -------------------------------- ### Manual AbortController with Complex Timeout Calculation Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-abort-signal-timeout.js.md This example demonstrates a manual AbortController setup where the timeout delay is calculated from multiple variables. AbortSignal.timeout() can directly accept such expressions. ```javascript const abortController = new AbortController(); setTimeout(() => abortController.abort(), (timeout + extraDelay)); fetch(url, {signal: abortController.signal}); ``` -------------------------------- ### minimumCases option example (>= 2) Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-switch.md Configures the rule to report if there are at least 2 cases. This example shows a case that would be flagged. ```javascript /* eslint unicorn/prefer-switch: ["error", {"minimumCases": 2}] */ // ❌ if (foo === 1) {} else if (foo === 2) {} ``` -------------------------------- ### Install ESLint and eslint-plugin-unicorn Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/readme.md Install the necessary packages for ESLint and the unicorn plugin as development dependencies. ```sh npm install --save-dev eslint eslint-plugin-unicorn ``` -------------------------------- ### Practical examples of padStart and padEnd Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-string-pad-start-end.md Demonstrates using padStart and padEnd for formatting table data and numbers for display. ```javascript // ✅ - Practical example: formatting table data const col1 = 'ID'.padEnd(10); const col2 = 'Name'.padEnd(20); const col3 = 'Value'.padStart(10); // ✅ - Padding numbers for display const hours = String(hours).padStart(2, '0'); const minutes = String(minutes).padStart(2, '0'); // → Outputs like "09:45" ``` -------------------------------- ### Run All Integration Tests Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/integration/readme.md Execute all integration tests from the project root. Ensure you have the necessary dependencies installed. ```bash npm run integration ``` -------------------------------- ### Custom Prefix Example (Passes) Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/consistent-boolean-name.md Demonstrates a boolean variable using a custom enabled prefix ('needs'). ```javascript const needsUpdate = true; ``` -------------------------------- ### Avoid constructing filename and dirname with fileURLToPath and path.dirname Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-import-meta-properties.js.md This example demonstrates an invalid approach to getting filename and dirname by using fileURLToPath and path.dirname. The rule recommends using import.meta.filename and import.meta.dirname directly. ```javascript const path = process.getBuiltinModule("node:path"); const { fileURLToPath } = process.getBuiltinModule("node:url"); const filename = fileURLToPath(import.meta.url); const dirname = path.dirname(filename); ``` ```javascript const path = process.getBuiltinModule("node:path"); const { fileURLToPath } = process.getBuiltinModule("node:url"); const filename = import.meta.filename; const dirname = path.dirname(filename); ``` ```javascript const path = process.getBuiltinModule("node:path"); const { fileURLToPath } = process.getBuiltinModule("node:url"); const filename = fileURLToPath(import.meta.url); const dirname = import.meta.dirname; ``` -------------------------------- ### Example of Number.parseInt usage Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-number-properties.md Demonstrates the correct usage of `Number.parseInt()`. ```javascript // ✅ const foo = Number.parseInt('10', 2); ``` -------------------------------- ### Configuration: Customizing Prefixes Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/consistent-boolean-name.md Example configuration to add a custom prefix ('needs') and disable a default prefix ('did'). ```javascript 'unicorn/consistent-boolean-name': [ 'error', { prefixes: { needs: true, did: false, }, }, ] ``` -------------------------------- ### Correct Class Member Order Example Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/consistent-class-member-order.md Illustrates the correct ordering of class members according to the rule. This example places static fields first, followed by private fields, public fields, and then the constructor. ```javascript class Foo { static staticField = 1; #privateField = 1; publicField = 1; constructor() {} } ``` -------------------------------- ### Decorator position 'before' examples Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/consistent-export-decorator-position.md Demonstrates the 'before' option, requiring decorators to appear before the 'export' keyword on the same line. ```javascript // eslint unicorn/consistent-export-decorator-position: ["error", "before"] // ❌ @decorator export default class Foo {} // ✅ @decorator export default class Foo {} ``` -------------------------------- ### Preferred switch statement example Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-switch.md Demonstrates the preferred switch statement structure for multiple conditions. ```javascript // ✅ switch (foo) { case 1: { // 1 break; } case 2: { // 2 break; } case 3: { // 3 break; } default: { // default } } ``` -------------------------------- ### Configuration: Enable `checkProperties` Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/consistent-boolean-name.md Example configuration to enable checking of object, class, and TypeScript property and method names. ```javascript 'unicorn/consistent-boolean-name': [ 'error', { checkProperties: true, }, ] ``` -------------------------------- ### Import Starting with 'get' Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-non-function-verb-prefix.js.md This rule flags imports where the imported name starts with 'get' but is not a function. Ensure that imported identifiers starting with 'get' are indeed functions. ```javascript import getName from "./module"; ``` -------------------------------- ### Type Annotation Starting with 'get' Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-non-function-verb-prefix.js.md This rule flags type annotations for variables or properties that start with 'get' but are not functions. Ensure that if an identifier starts with 'get', its type reflects a function. ```typescript let getName: string | (() => string); ``` -------------------------------- ### Prefer padStart() over manual string padding (start) Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-string-pad-start-end.js.md This snippet demonstrates manual string padding at the beginning of a string using `repeat()` and concatenation. The ESLint rule suggests replacing this with `String#padStart()` for better readability and conciseness. ```javascript const foo = `*`.repeat(10 - bar.length) + bar; ``` ```javascript const foo = "\t".repeat(width - bar.length) + bar; ``` ```javascript const foo = ( "*" .repeat( width - bar.length ) + bar ); ``` -------------------------------- ### Class Property Starting with 'get' Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-non-function-verb-prefix.js.md This rule flags class properties that start with 'get' but are not functions. Ensure properties like '#getName' are methods if they begin with 'get'. ```javascript class Person { #getName = "name"; } ``` -------------------------------- ### Class Property with Explicit Function Type Starting with 'get' Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-non-function-verb-prefix.js.md This rule flags class properties where the name starts with 'get' but the type is explicitly defined as a non-function type. Ensure that properties like 'getName' are functions if they start with 'get'. ```typescript class Person { getName: object = () => "name"; } ``` -------------------------------- ### Synchronous Resource Management with `using` Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-dispose.js.md Shows the recommended synchronous pattern using the `using` statement, which simplifies resource management and ensures proper disposal. ```javascript { using foo = /* keep me */ open(); use(foo); } ``` -------------------------------- ### Configure allowSimpleOperations to true Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-array-reduce.md Example of configuring the rule to allow simple operations, which is the default behavior. ```javascript /* eslint unicorn/no-array-reduce: ["error", {"allowSimpleOperations": true}] */ // ✅ array.reduce((total, item) => total + item) ``` -------------------------------- ### Incorrect usage of string.trimStart Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-uncalled-method.js.md This example highlights a string method `trimStart` being referenced directly. Use `trimStart()` to call the method correctly. ```javascript const method = (value as string).trimStart ``` -------------------------------- ### Class Accessor Starting with 'get' Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-non-function-verb-prefix.js.md This rule flags class accessors that start with 'get' but are not functions. Ensure properties like 'accessor getName' are methods if they begin with 'get'. ```javascript class Person { accessor getName = "name"; } ``` -------------------------------- ### Import with namespace starting with 'get' Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-non-function-verb-prefix.js.md This snippet demonstrates importing a module as a namespace where the namespace name starts with 'get'. The rule flags this because namespace imports are not functions. ```javascript import * as getModule from "./module"; ``` -------------------------------- ### Demonstrate trim(), trimStart(), and trimEnd() functionality Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-string-trim-start-end.md Illustrates the usage of `trim()`, `trimStart()`, and `trimEnd()` to remove whitespace from both ends, the beginning, and the end of a string, respectively. All three methods achieve the same outcome when applied to a string with leading and trailing whitespace. ```javascript // ✅ - All three do the same thing const str = ' hello world '; str.trim(); // Remove from both sides str.trimStart(); // Remove from beginning str.trimEnd(); // Remove from end ``` -------------------------------- ### Enum named 'get' Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-non-function-verb-prefix.js.md This snippet demonstrates an enum declaration with a name starting with 'get'. The rule flags this as enums are not functions. ```javascript enum getName { value } ``` -------------------------------- ### CommonJS import with 'get' name Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-non-function-verb-prefix.js.md This snippet shows a CommonJS style import where the imported variable name starts with 'get'. The rule flags this as it should be a function. ```javascript import getModule = require("./module"); ``` -------------------------------- ### Configure Lowercase Escape Sequences Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/escape-case.md This example shows how to configure the rule to enforce lowercase escape sequences. It includes the ESLint configuration and the corresponding incorrect (❌) and corrected (✅) code examples. ```js { 'unicorn/escape-case': ['error', 'lowercase'] } ``` ```js // ❌ const foo = '\xA9'; // ✅ const foo = '\xa9'; ``` ```js // ❌ const foo = '\uD834'; // ✅ const foo = '\ud834'; ``` ```js // ❌ const foo = '\u{1D306}'; // ✅ const foo = '\u{1d306}'; ``` ```js // ❌ const foo = '\cA'; // ✅ const foo = '\ca'; ``` -------------------------------- ### Import with aliased 'get' name Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-non-function-verb-prefix.js.md This snippet shows an import where the imported name is aliased to a name starting with 'get'. The rule flags this as the alias should be a function. ```javascript import {name as getName} from "./module"; ``` -------------------------------- ### Disabled Prefix Example (Fails) Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/consistent-boolean-name.md Demonstrates a boolean variable using a disabled default prefix ('did'). ```javascript const didUpdate = true; ``` -------------------------------- ### TODO in Block Comments with Package Installation Condition Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/expiring-todo-comments.md This example demonstrates using block comments for TODOs, with conditions based on installing a specific package. ```javascript /* * This code would be so easy if we used `popura` package helpers. * When you can, install `popura`, use it and remove dead code. * TODO [+popura]: Refactor to use `popura`. * * You can also use `popura-cli` since we want help on [feature]. * TODO [+popura-cli]: Document how to use `popura-cli`. */ ``` -------------------------------- ### Example: Spacing for Node Replacement with Braces Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/new-rule.md When replacing a node that starts or ends with braces (`{}`), ensure correct spacing if the replacement begins with a letter. This maintains valid JavaScript syntax, especially in constructs like `for...of` loops. ```javascript for(const{foo}of[]); ``` ```javascript // Good for(const foo of[]); // Bad for(constfooof[]); ``` -------------------------------- ### Function parameter named 'get' Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-non-function-verb-prefix.js.md This snippet shows a function with a parameter named 'getName'. The rule flags this because parameter names starting with 'get' should represent functions. ```javascript function run(getName: T) { return getName; } ``` -------------------------------- ### Asynchronous Resource Management with `await using` Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-dispose.js.md Presents the recommended asynchronous pattern using `await using`, which handles asynchronous disposal more cleanly and safely. ```javascript async function main() { { using foo = openFoo(); await using bar = openBar(); use(foo, bar); } } ``` -------------------------------- ### Prefer String#startsWith() over regex with ^ for new String() Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-string-starts-ends-with.js.md When testing if a string literal or a new String() object starts with a character using a regex like /^a/, prefer using the String#startsWith('a') method. This example shows the transformation for `new (SomeString)`. ```javascript `/^a/.test(new (SomeString))` ``` ```javascript (new (SomeString)).startsWith('a') ``` ```javascript String(new (SomeString)).startsWith('a') ``` ```javascript (new (SomeString))?.startsWith('a') ``` ```javascript (new (SomeString) ?? '').startsWith('a') ``` -------------------------------- ### Replace manual `try`/`finally` with `using` Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-dispose.md Use `using` for synchronous resource disposal. The resource must implement `Symbol.dispose`. ```javascript const file = open(); try { read(file); } finally { file.close(); } ``` ```javascript { using file = open(); read(file); } ``` -------------------------------- ### Invalid fetch(url, {method: "GET", body}) Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-invalid-fetch-options.js.md This example shows an explicit attempt to use `fetch` with the 'GET' method and a `body`. The rule correctly identifies this as an error because the 'GET' method does not permit a request body. ```javascript fetch(url, {method: "GET", body}) ``` -------------------------------- ### Example: Disabling all rules (❌) vs. specific rule (✅) in a file Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-abusive-eslint-disable.md Demonstrates the incorrect usage of disabling all rules versus the correct usage of specifying the `no-console` rule for the entire file. ```javascript // ❌ /* eslint-disable */ console.log(message); // ✅ /* eslint-disable no-console */ console.log(message); ``` -------------------------------- ### Invalid Boolean Name Example Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/consistent-boolean-name.js.md This example shows an invalid boolean variable name that does not start with a recognized prefix. The suggested output provides multiple valid alternatives. ```javascript const completed = Number.isFinite(value); ``` ```javascript const isCompleted = Number.isFinite(value); ``` ```javascript const areCompleted = Number.isFinite(value); ``` ```javascript const hasCompleted = Number.isFinite(value); ``` ```javascript const haveCompleted = Number.isFinite(value); ``` ```javascript const canCompleted = Number.isFinite(value); ``` ```javascript const shouldCompleted = Number.isFinite(value); ``` ```javascript const wasCompleted = Number.isFinite(value); ``` ```javascript const wereCompleted = Number.isFinite(value); ``` ```javascript const didCompleted = Number.isFinite(value); ``` ```javascript const willCompleted = Number.isFinite(value); ``` -------------------------------- ### Convert async operations with regex to String#startsWith() Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-string-starts-ends-with.js.md This example shows how to refactor asynchronous code that uses regex for prefix checking. It converts `regex.test(await asyncOperation())` to `(await asyncOperation()).startsWith(prefix)`, offering several suggestions for handling potential null or undefined values. ```javascript async function a() {return (await foo()).startsWith('a')} ``` ```javascript async function a() {return String(await foo()).startsWith('a')} ``` ```javascript async function a() {return (await foo())?.startsWith('a')} ``` ```javascript async function a() {return ((await foo()) ?? '').startsWith('a')} ``` -------------------------------- ### Invalid Code Example: Multiple shared statements Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-hoisting-branch-code.js.md Shows an example with multiple statements ('x; y;') that are identical at the start of both conditional branches. The rule advises moving these common statements out. ```javascript if (a) { x; y; foo(); } else { x; y; bar(); } ``` -------------------------------- ### Configuration: checkAllIndexAccess enabled Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-at.md Example of ESLint configuration to enable checking of all index accesses, not just negative ones. ```javascript { 'unicorn/prefer-at': [ 'error', { checkAllIndexAccess: true } ] } ``` -------------------------------- ### Configuration: getLastElementFunctions Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-at.md Example of ESLint configuration to specify custom functions for getting the last element. ```javascript { 'unicorn/prefer-at': [ 'error', { getLastElementFunctions: [ 'getLast', 'utils.lastElement' ] } ] } ``` -------------------------------- ### Import General Utility Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/CLAUDE.md Import general helper functions from the `rules/utils/index.js` barrel file. ```javascript import {needsSemicolon} from './utils/index.js' ``` -------------------------------- ### Invalid GET with body vs. Valid POST with body in fetch() Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-invalid-fetch-options.md This example contrasts an invalid `fetch()` call with a `GET` method and a `body` against a valid call using the `POST` method with a `body`. The rule flags the former. ```javascript // ❌ const response = await fetch('/', {method: 'GET', body: 'foo=bar'}); // ✅ const response = await fetch('/', {method: 'POST', body: 'foo=bar'}); ``` -------------------------------- ### minimumCases option example (>= 4) Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-switch.md Configures the rule to only report if there are at least 4 cases. The default branch does not count. ```javascript /* eslint unicorn/prefer-switch: ["error", {"minimumCases": 4}] */ // ✅ if (foo === 1) {} else if (foo === 2) {} else if (foo === 3) {} // ✅ if (foo === 1) {} else if (foo === 2) {} else if (foo === 3) {} else {} // ✅ if (foo === 1) {} else if (foo === 2 || foo === 3) {} else if (foo === 4) {} ``` -------------------------------- ### Correct 'Nodejs' to 'Node.js' Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/comment-content.js.md This example demonstrates correcting 'Nodejs' to 'Node.js'. The 'checkUniformCase' option must be false. ```javascript // run on Nodejs ``` -------------------------------- ### Basic Identifier Matching Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/id-match.md Enforces that all identifiers match the provided regular expression. This example shows a basic setup where only lowercase identifiers are allowed. ```javascript /* eslint unicorn/id-match: ["error", "^[a-z]+$"] */ // ❌ const foo$ = 1; // ✅ const foo = 1; ``` -------------------------------- ### Math.max() and Math.min() for clamping Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-flat-math-min-max.md This example shows a valid use case for nested Math.max() and Math.min() when clamping a value within a range. ```javascript // ✅ const clamped = Math.max(Math.min(value, upper), lower); ``` -------------------------------- ### Move common setup code before if/else Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-hoisting-branch-code.js.md When multiple branches of an if/else statement start with the same code, move that code before the conditional block to avoid repetition. ```javascript if (a) { x; foo(); } else { x; bar(); } ``` ```javascript x; if (a) { foo(); } else { bar(); } ``` -------------------------------- ### Invalid: Function parameter 'getName' is not a function Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-non-function-verb-prefix.js.md This example shows an invalid function definition where the parameter 'getName' is used, but it should be a function due to the 'get' prefix. ```typescript function run(getName: string) { return getName; } ``` -------------------------------- ### Use Array#push() for efficient array accumulation Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-array-concat-in-loop.md This example demonstrates the recommended approach using `Array#push()` with the spread syntax to efficiently add elements from chunks to the result array within a loop. ```javascript const result = []; for (const chunk of chunks) { result.push(...chunk); } ``` -------------------------------- ### Invalid: Variable 'getName' is not a function Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-non-function-verb-prefix.js.md This example shows an invalid usage where 'getName' is declared as a string, violating the rule because 'get' is a verb that should prefix a function. ```typescript const getName = "name"; ``` -------------------------------- ### Configuration with Custom Selectors Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/template-indent.md An example configuration that uses ESLint selectors to indent all template literals, regardless of tags or function calls. ```json { 'unicorn/template-indent': [ 'warn', { tags: [], functions: [], selectors: [ 'TemplateLiteral' ] } ] } ``` -------------------------------- ### Configure targets with a string Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-unnecessary-polyfills.md Specify target versions using a Browserslist query string for the 'targets' option. ```javascript 'unicorn/no-unnecessary-polyfills': [ 'error', { targets: 'node >=12', }, ] ``` -------------------------------- ### Invalid Boolean Name: 'willow' Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/consistent-boolean-name.js.md This example shows a boolean variable 'willow' that does not start with a conventional boolean prefix. The linter suggests renaming it to 'isWillow' or other valid prefixes. ```javascript const willow = true; ``` -------------------------------- ### Correct Method Order Example Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/consistent-class-member-order.md Presents the correct ordering for class methods, with static methods first, followed by private methods, and then public methods. This ensures a consistent and predictable method structure. ```javascript class Foo { static staticMethod() {} #privateMethod() {} publicMethod() {} } ``` -------------------------------- ### Move common initialization code before if statement Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-hoisting-branch-code.js.md When multiple branches of an if/else statement start with the same code, move that code before the if statement to avoid repetition. This applies to the `x;` statement in the example. ```javascript class C { static { if (a) { x; foo(); } else { x; bar(); } } } ``` ```javascript class C { static { x; if (a) { foo(); } else { bar(); } } } ``` -------------------------------- ### Invalid boolean method name Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/consistent-boolean-name.js.md This example demonstrates a method 'completed' within an object that returns a boolean. The rule flags the method name 'completed' for not starting with a boolean prefix. ```javascript const task = {completed() { return true; }}; ``` -------------------------------- ### Using AbortSignal.any() with explicit signals Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-abort-signal-any.md Demonstrates the correct usage of `AbortSignal.any()` with a list of specific signals, providing a cleaner alternative to manual event forwarding. ```javascript const abortSignal = AbortSignal.any([firstSignal, secondSignal]); await fetch(url, {signal: abortSignal}); ``` -------------------------------- ### Prefer `export…from` for default exports Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-export-from.md Use `export {default} from './foo.js';` instead of importing and then exporting the default. ```javascript // ❌ import defaultExport from './foo.js'; export default defaultExport; // ✅ export {default} from './foo.js'; ``` -------------------------------- ### Invalid export with boolean name 'completed' Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/consistent-boolean-name.js.md Boolean variables exported directly should start with a valid prefix. This example shows an invalid export where 'completed' does not adhere to the naming convention. ```javascript export const completed = true; ``` -------------------------------- ### Prefer padStart over manual padding with repeat Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-string-pad-start-end.md Use padStart for clearer intent and to avoid potential RangeErrors with String#repeat(). ```javascript const formatted = '*'.repeat(10 - name.length) + name; // ✅ - Clearer intent with padStart const formatted = name.padStart(10, '*'); ``` -------------------------------- ### Invalid Boolean Naming Example Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/consistent-boolean-name.js.md Demonstrates a violation where a boolean variable 'completed' does not start with a recognized boolean prefix. The rule suggests renaming it to a more conventional name like 'isCompleted'. ```javascript const map = new Map(); const completed = map.has(key); ``` -------------------------------- ### Empty File Input Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-empty-file.js.md This snippet shows an example of a completely empty file that violates the unicorn/no-empty-file rule. ```javascript ␊ ``` -------------------------------- ### Invalid Boolean Name Example Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/consistent-boolean-name.js.md Demonstrates an invalid boolean variable name that violates the naming convention. The suggested fix is to rename the variable to start with an appropriate boolean prefix. ```javascript const completed = Number.isSafeInteger(value); ``` -------------------------------- ### Unwrap and Continue Comment with Global State Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-manually-wrapped-comments.js.md This example shows the rule's behavior with comments related to global state initialization that are manually split across lines. The output merges these lines into a single, coherent comment. ```javascript // Global state is initialized but // the next step runs later ``` -------------------------------- ### Class Property with 'get' Prefix Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-non-function-verb-prefix.js.md This example shows a class property named `getName` assigned a string value. As it's not a function, the rule flags this as a violation of the naming convention. ```javascript class Person { getName = "name"; } ``` -------------------------------- ### Using 'using' for outer resource management Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-dispose.js.md This example demonstrates how to refactor the outer try/finally block to use the 'using' keyword for explicit resource management. ```javascript { using outer = open(); const inner = open(); try { use(inner); } finally { inner.close(); } } ``` -------------------------------- ### Invalid Boolean Function Name Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/consistent-boolean-name.js.md This example shows a function `completed` that returns a boolean but does not start with a valid boolean prefix. The ESLint error suggests renaming it to `isCompleted` or another appropriate prefix. ```javascript function completed(value) { return value === true; } completed(true); ``` -------------------------------- ### Invalid Boolean Name Example Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/consistent-boolean-name.js.md Demonstrates a violation of the consistent boolean naming rule where a boolean variable 'completed' does not start with a valid prefix. The rule suggests renaming it to 'isCompleted' or other valid alternatives. ```javascript const completed = Atomics.isLockFree(4); ``` ```javascript const isCompleted = Atomics.isLockFree(4); ``` -------------------------------- ### Prefer trimStart() over trimLeft() Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-string-trim-start-end.md Use `String#trimStart()` instead of the deprecated `String#trimLeft()` for removing whitespace from the beginning of a string. ```javascript // ❌ - Deprecated names const name = ' John '.trimLeft(); // ✅ - Preferred method const name = ' John '.trimStart(); ``` -------------------------------- ### Prefer new Map() for map-like operations Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-map-from-entries.md Use `new Map()` when the resulting object is primarily used with map-like operations. This example demonstrates the correct usage with `Map` methods like `has` and `get`. ```javascript const object = new Map(Object.entries(source)); if (object.has('foo')) { console.log(object.get('foo')); } ``` -------------------------------- ### Prefer Math.hypot() for multiple arguments with mixed exponentiation Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-modern-math-apis.js.md This example shows how to replace `Math.sqrt(a ** 2 + b ** 2 + c ** 2)` with `Math.hypot(a, b, c)` for calculating the hypotenuse of a multi-dimensional vector, ensuring better precision. ```javascript Math.sqrt(a ** 2 + b ** 2 + c ** 2) ``` ```javascript Math.hypot(a, b, c) ``` -------------------------------- ### Prefer `.at()` over `.slice()` followed by element access Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-at.js.md This example illustrates refactoring code where `.slice()` is used to get a single-element array, and then the first element is accessed. The `.at()` method achieves the same result more efficiently. ```javascript (( array.slice(-1)[0] )); ``` ```javascript (( array.at(-1) )); ``` -------------------------------- ### Hoist common code from if/else if/else chains Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-hoisting-branch-code.js.md For longer conditional chains like if/else if/else, any code that is common to the start of multiple branches should be hoisted. This example demonstrates hoisting from an if/else if/else structure. ```javascript if (ready) { value; foo(); } else if (initialize()) { value; bar(); } else { value; baz(); } ``` ```javascript value; if (ready) { foo(); } else if (initialize()) { bar(); } else { baz(); } ``` -------------------------------- ### Replace manual `try`/`finally` with `await using` Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-dispose.md Use `await using` for asynchronous resource disposal. The resource must implement `Symbol.asyncDispose`. ```javascript async function run() { const connection = await connect(); try { await query(connection); } finally { await connection.close(); } } ``` ```javascript async function run() { await using connection = await connect(); await query(connection); } ``` -------------------------------- ### Import General Utility Helper Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/AGENTS.md Import general utility functions from the `./utils/index.js` barrel file. ```javascript import {getParenthesizedRange} from './utils/index.js' ``` -------------------------------- ### Invalid Private Boolean Getter Name Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/consistent-boolean-name.js.md This example shows an invalid private boolean getter name '#ready'. The rule mandates that boolean getters, even private ones, must start with a conventional prefix. ```javascript class Task { get #ready(): boolean { return true; } } ``` -------------------------------- ### Disallow empty file with only whitespace Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-empty-file.js.md This example demonstrates an empty file containing only whitespace, which is also disallowed. ```javascript ``` -------------------------------- ### Function with invalid boolean name Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/consistent-boolean-name.js.md Functions returning booleans should have names starting with 'is', 'are', 'has', 'have', 'can', 'should', 'was', 'were', 'did', or 'will'. This example shows an invalid naming convention. ```javascript function completed() { return true; } ``` -------------------------------- ### Creating a New ESLint Unicorn Rule Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/CLAUDE.md Follow these steps to create a new rule: scaffold, write tests, implement the rule, document it, verify tests, and then run linting, dogfooding, and final tests before pushing. ```text 1. Run `npm run create-rule` to scaffold the rule file, test file, and doc file. This also regenerates `rules/index.js` and updates doc headers. 2. Write tests in `test/.js` before implementing the rule. 3. Implement the rule in `rules/.js`. 4. Write documentation in `docs/rules/.md` (below the auto-generated header). 5. Run `npx ava test/.js` to verify tests pass. 6. Before pushing, run lint (`npm run lint:js`, which runs `eslint` — see [Linting](#linting)), dogfooding (`npm run run-rules-on-codebase`), and then `npm test`. If dogfooding finds intentional internal patterns, disable the rule in `eslint.dogfooding.config.js` instead of adding repo-specific heuristics. ``` -------------------------------- ### Prefer 'using' over try/finally for multiple resources Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-dispose.js.md Use the 'using' keyword for managing multiple resources to simplify cleanup logic compared to a manual try/finally block. ```javascript const foo = openFoo(); const bar = openBar(); try { use(foo, bar); } finally { bar.destroy(); foo.close(); } ``` ```javascript { using foo = openFoo(); using bar = openBar(); use(foo, bar); } ``` -------------------------------- ### Prefer URL#href over explicit string conversion Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-url-href.js.md This example shows an explicit call to `String()` on a `new URL()` object. The rule suggests using the `.href` property for a more direct and intended way to get the URL string. ```javascript const foo = 1 String((new URL(value))) ``` -------------------------------- ### Combining re-exports with `export ... from` Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-export-from.js.md This example demonstrates how to combine re-exports of different modules into a single `export ... from` statement. It shows re-exporting `bar` and the default import as `foo` from 'foo'. ```javascript import foo from 'foo'; export {foo}; export {bar} from 'foo'; ``` ```javascript export {bar, default as foo} from 'foo'; ``` -------------------------------- ### Invalid Boolean Name - ESLint Plugin Unicorn Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/consistent-boolean-name.js.md This example shows an invalid boolean variable name 'completed' which does not start with a recognized boolean prefix. The error message provides suggestions for renaming the variable to adhere to the rule. ```javascript const text = "unicorn"; const completed = text.isWellFormed(); ``` -------------------------------- ### Prefer `download` over `downLoad` Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/consistent-compound-words.js.md This snippet demonstrates the rule's suggestion to use `download` instead of `downLoad` for better consistency. ```javascript const downLoad = fetchArchive(); ``` ```javascript const download = fetchArchive(); ``` -------------------------------- ### Fixing 'key in object' boolean name Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/consistent-boolean-name.js.md When a boolean variable is declared using the 'in' operator, its name should start with a recognized boolean prefix. This example shows how to rename a variable like 'completed' to a more descriptive name such as 'isCompleted'. ```javascript const completed = key in object; ``` ```javascript const isCompleted = key in object; ``` -------------------------------- ### Invalid fetch(url, {method: "HEAD", body}) Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-invalid-fetch-options.js.md This example highlights an invalid usage of `fetch` with the 'HEAD' method and a `body`. The rule flags this because 'HEAD' requests, like 'GET', do not support a request body. ```javascript fetch(url, {method: "HEAD", body}) ``` -------------------------------- ### Use `new` for WebAssembly Instance Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/new-for-builtins.js.md Directly calling `WebAssembly.Instance()` is incorrect. Use `new WebAssembly.Instance()` for proper instantiation. ```javascript const foo = WebAssembly.Instance(module, imports) ``` ```javascript const foo = new WebAssembly.Instance(module, imports) ``` -------------------------------- ### JSON file read with options (string) Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/consistent-json-file-read.md Example of reading a JSON file with additional options, which the rule leaves unchanged. ```javascript // ✅ const promise = fs.readFile('./package.json', {encoding: 'utf8', signal}); const packageJson = JSON.parse(await promise); ``` -------------------------------- ### Invalid fetch() with duplicate body properties Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-invalid-fetch-options.js.md This example illustrates an invalid `fetch` call with duplicate `body` properties in the options object. The latter `body` property overwrites the former, and the rule flags the presence of a `body` when the method is 'GET'. ```javascript fetch(url, { body: undefined, body: 'foo=bar', }); ``` -------------------------------- ### Re-exporting types and values with mixed `export ... from` Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-export-from.js.md This example shows a scenario where types and values are exported separately, and how the rule suggests consolidating them into `export ... from` statements for better organization. ```javascript import type { foo } from 'foo'; export type { foo }; export { baz } from "foo"; export type { bar } from "foo"; ``` ```javascript export { baz } from "foo"; export type { bar, foo } from "foo"; ``` -------------------------------- ### lib.Object.create(null) should be lib.Object.create(undefined) Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-null.js.md This example highlights an invalid use of `null` with `lib.Object.create`. The rule advises using `undefined` in this context. ```javascript lib.Object.create(null) ``` ```javascript lib.Object.create(undefined) ``` -------------------------------- ### Allow non-function values for specific verb prefixes Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-non-function-verb-prefix.md Shows examples of identifiers that are allowed even if they start with a verb prefix, such as 'getter', 'get_name', or 'GET_NAME'. These are typically not considered function-style verb prefixes by the rule's default configuration. ```javascript // ✅ const getter = 'name'; const get_name = 'name'; const GET_NAME = 'name'; ``` -------------------------------- ### Prefer String#startsWith() over regex with '^' for optional chaining Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-string-starts-ends-with.js.md This example shows how the rule handles cases involving optional chaining in the property access. It recommends String#startsWith() and offers variations for different error-handling strategies. ```javascript 1 | /^a/.test(foo?.bar) ``` ```javascript 1 | foo?.bar.startsWith('a') ``` ```javascript 1 | String(foo?.bar).startsWith('a') ``` ```javascript 1 | foo?.bar?.startsWith('a') ``` ```javascript 1 | (foo?.bar ?? '').startsWith('a') ``` -------------------------------- ### Prefer String#at() for single character access with reversed index calculation Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-at.js.md This example shows the replacement of String#substring() with String#at() when the start index is calculated as `1 + index` and the end index is `index`. String#at() simplifies this by directly taking the intended index. ```javascript string.substring(1 + index, index) ``` ```javascript string.at(index) ``` -------------------------------- ### Example: Leading Semicolons for Node Replacement Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/new-rule.md When replacing a node that might be preceded by code, ensure that a leading semicolon is added if the replacement starts with a bracket or parenthesis to prevent syntax errors. This handles cases where the preceding code doesn't end with a semicolon. ```javascript foo const bar = [1] bar.forEach(number => { console.log(number) }) ``` ```javascript // Good foo ;[1].forEach(number => { console.log(number) }) // Bad foo [1].forEach(number => { console.log(number) }) ``` -------------------------------- ### Refactor common setup and teardown in if/else branches Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-hoisting-branch-code.js.md This snippet illustrates refactoring an if-else statement where both branches share common setup and teardown logic. The setup code is moved before the if-else, and the teardown code is moved after. ```javascript if (a) { setup(); foo(); teardown(); } else { setup(); bar(); teardown(); } ``` ```javascript setup(); if (a) { foo(); teardown(); } else { bar(); teardown(); } ``` ```javascript if (a) { setup(); foo(); } else { setup(); bar(); } teardown(); ``` -------------------------------- ### Prefer RegExp#test() over String#match() with RegExp constructor Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-regexp-test.js.md This example shows how to replace `String#match()` with `RegExp#test()` when the regular expression is created using the `new RegExp()` constructor. ```javascript if ((foo).match(new SomeRegExp)) {} ``` ```javascript if ((new SomeRegExp).test(foo)) {} ``` -------------------------------- ### Using 'using' for inner resource management Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-dispose.js.md This example shows the refactoring of the inner try/finally block to utilize the 'using' keyword for managing the inner resource. ```javascript const outer = open(); try { { using inner = open(); use(inner); } } finally { outer.close(); } ``` -------------------------------- ### Prefer import.meta.filename and import.meta.dirname Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-import-meta-properties.js.md Avoid constructing `filename` and `dirname` using `fileURLToPath` and `path.dirname`. Use `import.meta.filename` and `import.meta.dirname` directly. ```javascript const path = process.getBuiltinModule("path"); const { fileURLToPath } = process.getBuiltinModule("url"); const filename = fileURLToPath(import.meta.url); const dirname = path.dirname(filename); ``` ```javascript const path = process.getBuiltinModule("path"); const { fileURLToPath } = process.getBuiltinModule("url"); const filename = import.meta.filename; const dirname = import.meta.dirname; ``` -------------------------------- ### Disallow `get then()` Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-thenable.js.md Use this rule to disallow `get then()` syntax. This prevents accidental creation of thenable objects. ```javascript const foo = {get then() {}} ``` -------------------------------- ### Configure targets with an array of strings Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-unnecessary-polyfills.md Specify target versions using an array of Browserslist queries for the 'targets' option. ```javascript 'unicorn/no-unnecessary-polyfills': [ 'error', { targets: [ 'node 14.1.0', 'chrome 95', ], }, ] ``` -------------------------------- ### Convert to String#startsWith() with Optional Chaining Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-string-starts-ends-with.js.md Uses optional chaining (`?.`) to safely call `startsWith()` when the target might be nullish. This avoids errors if the object is null or undefined. ```javascript /* 1 */ ( /* 2 */ /* 3 */ ( /* 10 */ /* 11 */ a /* 12 */ /* 13 */ ) /* 14 */ ) /* 4 */ ) /* 5 */ ) /* 6 */ . /* 7 */ test /* 8 */ ( /* 9 */ ( /* 10 */ /* 11 */ a /* 12 */ /* 13 */ ) /* 14 */ ) /* 15 */ ``` ```javascript /* 1 */ ( /* 2 */ /* 3 */ ( /* 10 */ /* 11 */ a /* 12 */ /* 13 */ ) /* 14 */ ) /* 4 */ ) /* 5 */ ) /* 6 */ ?. /* 7 */ startsWith /* 8 */ ( /* 9 */ 'a' /* 14 */ ) /* 15 */ ``` -------------------------------- ### Disallow non-function values with 'get' prefix Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-non-function-verb-prefix.md Reports when a variable prefixed with 'get' is assigned a non-function value. Ensure such variables are always functions. ```javascript // ❌ const getName = 'Sindre'; // ✅ const getName = () => 'Sindre'; ``` -------------------------------- ### Replace try...finally with using for connection disposal Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-dispose.js.md Shows how to convert a `try...finally` pattern for managing a connection's lifecycle to the more modern `using` statement. ```javascript const connection = connect(); try { use(connection); } finally { connection.destroy(); } ``` ```javascript { using connection = connect(); use(connection); } ``` -------------------------------- ### Multi-key comparator example Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-simple-sort-comparator.md This rule intentionally ignores multi-key comparators where different properties are used as tiebreakers. The example shows sorting by `foo` then `bar`. ```javascript // ✅ Multi-key comparator, not reported array.sort((a, b) => a.foo - b.foo || a.bar - b.bar); ``` -------------------------------- ### All ESLint Config with Unicorn Plugin Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/readme.md Use the 'all' preset to enable every rule except deprecated ones. This provides maximum rule coverage. ```js import unicorn from 'eslint-plugin-unicorn'; import {defineConfig} from 'eslint/config'; export default defineConfig([ // … { files: ['**/*.js'], extends: [unicorn.configs.all], rules: { 'unicorn/prefer-module': 'warn', }, }, ]); ``` -------------------------------- ### Disallow computed property name `get `then`()` Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-thenable.js.md Use this rule to disallow computed property names that resolve to `get `then`()`. This prevents accidental creation of thenable objects. ```javascript const foo = {get [`then`]() {}} ``` -------------------------------- ### Disallow computed property name `get then()` Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-thenable.js.md Use this rule to disallow computed property names that resolve to `get then()`. This prevents accidental creation of thenable objects. ```javascript const foo = {get ["then"]() {}} ``` -------------------------------- ### Customizing verb prefixes for the rule Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-non-function-verb-prefix.md Demonstrates how to configure the rule to check for custom verb prefixes, such as 'build'. This example shows a violation when 'buildName' is assigned a string instead of a function. ```javascript /* eslint unicorn/no-non-function-verb-prefix: ["error", {"verbs": ["build"]}] */ // ❌ const buildName = 'name'; // ✅ const buildName = () => 'name'; ``` -------------------------------- ### Function Parameter with 'get' Prefix Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-non-function-verb-prefix.js.md This snippet shows a function parameter named `getName` which is incorrectly prefixed with 'get' as it's not a function. The rule flags this as an error. ```javascript function run({getName}: {getName: string}) { return getName; } ``` -------------------------------- ### Prefer Object.defineProperties for prototype properties Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-object-define-properties.js.md This example demonstrates the rule's application to defining properties on a prototype. Multiple `Object.defineProperty()` calls on `Foo.prototype` are refactored into a single `Object.defineProperties()` call. ```javascript Object.defineProperty(Foo.prototype, "bar", {value: 1}); Object.defineProperty(Foo.prototype, "baz", {value: 2}); ``` ```javascript Object.defineProperties(Foo.prototype, { bar: {value: 1}, baz: {value: 2}, }); ``` -------------------------------- ### Disallow body with GET method in fetch() Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-invalid-fetch-options.md This snippet shows an invalid usage where a `body` is provided with a `GET` method in `fetch()`. The rule flags this to prevent a `TypeError`. ```javascript // ❌ const response = await fetch('/', {body: 'foo=bar'}); ``` -------------------------------- ### Synchronous Resource Management with `try...finally` Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-dispose.js.md Demonstrates the traditional synchronous pattern of opening a resource, using it, and then closing it in a `finally` block. This pattern is flagged by the rule. ```javascript const foo = /* keep me */ open(); try { use(foo); } finally { foo.close(); } ``` -------------------------------- ### Configure ESLint for Non-JavaScript Files Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/readme.md This example demonstrates how to configure ESLint to use Unicorn rules across different file types, including JavaScript, JSON, CSS, HTML, and Markdown. It shows how to extend Unicorn's recommended configs and selectively enable rules for specific file types using the `files` property. ```javascript import css from '@eslint/css'; import json from '@eslint/json'; import markdown from '@eslint/markdown'; import html from '@html-eslint/eslint-plugin'; import unicorn from 'eslint-plugin-unicorn'; import {defineConfig} from 'eslint/config'; export default defineConfig([ { files: ['**/*.js'], extends: [unicorn.configs.recommended], }, { files: ['**/*.json'], plugins: { json, unicorn, }, language: 'json/json', rules: { 'unicorn/no-empty-file': 'error', 'unicorn/prefer-https': 'error', }, }, { files: ['**/*.css'], plugins: { css, unicorn, }, language: 'css/css', rules: { 'unicorn/prefer-https': 'error', 'unicorn/text-encoding-identifier-case': 'error', }, }, { files: ['**/*.html'], plugins: { html, unicorn, }, language: 'html/html', rules: { 'unicorn/no-invalid-file-input-accept': 'error', 'unicorn/prefer-https': 'error', }, }, { files: ['**/*.md'], plugins: { markdown, unicorn, }, language: 'markdown/commonmark', rules: { 'unicorn/expiring-todo-comments': 'error', 'unicorn/prefer-https': 'error', }, }, ]); ``` -------------------------------- ### Refactor duplicate code at the start of conditional branches Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/prefer-hoisting-branch-code.js.md When multiple branches of a conditional statement start with the same code, move that common code before the conditional to avoid repetition. ```javascript switch (value) { case 1: if (a) { x; foo(); } else { x; bar(); } } ``` ```javascript switch (value) { case 1: x; if (a) { foo(); } else { bar(); } } ``` -------------------------------- ### Recommended ESLint Config with Unicorn Plugin Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/readme.md Use the 'recommended' preset to enforce good practices. This config enables a curated set of rules. ```js import unicorn from 'eslint-plugin-unicorn'; import {defineConfig} from 'eslint/config'; export default defineConfig([ // … { files: ['**/*.js'], extends: [unicorn.configs.recommended], rules: { 'unicorn/prefer-module': 'warn', }, }, ]); ``` -------------------------------- ### Invalid fetch() with body on GET Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/no-invalid-fetch-options.js.md This snippet demonstrates an invalid usage of `fetch` where a `body` option is provided while the HTTP method is implicitly 'GET'. The rule flags this as an error. ```javascript fetch(url, {body}, extraArgument) ``` -------------------------------- ### Correctly Instantiate Map Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/test/snapshots/new-for-builtins.js.md Use `new Map()` instead of `Map()` to correctly instantiate a `Map`. This applies even when providing initial entries. ```javascript const foo = (( Map ))() ``` ```javascript const foo = new (( Map ))() ``` ```javascript const foo = Map([['foo', 'bar'], ['unicorn', 'rainbow']]) ``` ```javascript const foo = new Map([['foo', 'bar'], ['unicorn', 'rainbow']]) ```