From 4763941ce22508dbc8a24e3f66be847161eec2a4 Mon Sep 17 00:00:00 2001 From: therewillbecode Date: Mon, 17 Feb 2025 20:52:32 +0000 Subject: [PATCH] Add correctness examples to no-sparse-arrays eslint rule --- .../src/rules/eslint/no_sparse_arrays.rs | 36 +++++++++++++++++-- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/crates/oxc_linter/src/rules/eslint/no_sparse_arrays.rs b/crates/oxc_linter/src/rules/eslint/no_sparse_arrays.rs index e102fcc62fe07..09affda8890b3 100644 --- a/crates/oxc_linter/src/rules/eslint/no_sparse_arrays.rs +++ b/crates/oxc_linter/src/rules/eslint/no_sparse_arrays.rs @@ -14,13 +14,43 @@ declare_oxc_lint!( /// /// ### Why is this bad? /// - /// The confusion around sparse arrays is enough that it’s recommended to avoid using them unless you are certain that they are useful in your code. + /// Take the following example: /// - /// ### Example + /// ```javascript + /// const items = [,,]; + /// ``` + /// + /// While the items array in this example has a length of 2, there are actually + /// no values in items[0] or items[1]. The fact that the array literal is + /// valid with only commas inside, coupled with the length being set and + /// actual item values not being set, make sparse arrays confusing for many + /// developers. + /// + /// The confusion around sparse arrays is enough that it’s recommended to + /// avoid using them unless you are certain that they are useful in your + /// code. + /// + /// + /// ### Examples + /// + /// Examples of **incorrect** code for this rule: /// ```javascript /// var items = [,,]; + /// ``` + /// + /// ```javascript /// var colors = [ "red",, "blue" ]; /// ``` + /// + /// Examples of **correct** code for this rule: + /// ```javascript + /// var items = []; + /// ``` + /// + /// // trailing comma (after the last element) is not a problem + /// ```javascript + /// var colors = [ "red", "blue", ]; + /// ``` NoSparseArrays, eslint, correctness @@ -79,7 +109,7 @@ impl Rule for NoSparseArrays { fn test() { use crate::tester::Tester; - let pass = vec!["var a = [ 1, 2, ]"]; + let pass = vec!["var a = [ 1, 2, ]", "var a = [];"]; let fail = vec![ "var a = [,];",