|
| 1 | +use oxc_macros::declare_oxc_lint; |
| 2 | + |
| 3 | +use crate::rule::Rule; |
| 4 | + |
| 5 | +#[derive(Debug, Default, Clone)] |
| 6 | +pub struct PreferIncludes; |
| 7 | + |
| 8 | +declare_oxc_lint!( |
| 9 | + /// ### What it does |
| 10 | + /// |
| 11 | + /// Enforce using `.includes()` instead of `.indexOf() !== -1` or `/regex/.test()`. |
| 12 | + /// |
| 13 | + /// ### Why is this bad? |
| 14 | + /// |
| 15 | + /// `.includes()` is more readable and expressive than checking `.indexOf() !== -1`. |
| 16 | + /// It clearly communicates the intent to check for the presence of a value. |
| 17 | + /// Additionally, for simple string searches, `.includes()` is often preferred over |
| 18 | + /// regex `.test()` for better performance and clarity. |
| 19 | + /// |
| 20 | + /// ### Examples |
| 21 | + /// |
| 22 | + /// Examples of **incorrect** code for this rule: |
| 23 | + /// ```ts |
| 24 | + /// // Using indexOf |
| 25 | + /// const str = 'hello world'; |
| 26 | + /// if (str.indexOf('world') !== -1) { |
| 27 | + /// console.log('found'); |
| 28 | + /// } |
| 29 | + /// |
| 30 | + /// if (str.indexOf('world') != -1) { |
| 31 | + /// console.log('found'); |
| 32 | + /// } |
| 33 | + /// |
| 34 | + /// if (str.indexOf('world') > -1) { |
| 35 | + /// console.log('found'); |
| 36 | + /// } |
| 37 | + /// |
| 38 | + /// // Using regex test for simple strings |
| 39 | + /// if (/world/.test(str)) { |
| 40 | + /// console.log('found'); |
| 41 | + /// } |
| 42 | + /// |
| 43 | + /// // Arrays |
| 44 | + /// const arr = [1, 2, 3]; |
| 45 | + /// if (arr.indexOf(2) !== -1) { |
| 46 | + /// console.log('found'); |
| 47 | + /// } |
| 48 | + /// ``` |
| 49 | + /// |
| 50 | + /// Examples of **correct** code for this rule: |
| 51 | + /// ```ts |
| 52 | + /// // Using includes for strings |
| 53 | + /// const str = 'hello world'; |
| 54 | + /// if (str.includes('world')) { |
| 55 | + /// console.log('found'); |
| 56 | + /// } |
| 57 | + /// |
| 58 | + /// // Using includes for arrays |
| 59 | + /// const arr = [1, 2, 3]; |
| 60 | + /// if (arr.includes(2)) { |
| 61 | + /// console.log('found'); |
| 62 | + /// } |
| 63 | + /// |
| 64 | + /// // Complex regex patterns are allowed |
| 65 | + /// if (/wo+rld/.test(str)) { |
| 66 | + /// console.log('found'); |
| 67 | + /// } |
| 68 | + /// |
| 69 | + /// // Regex with flags |
| 70 | + /// if (/world/i.test(str)) { |
| 71 | + /// console.log('found'); |
| 72 | + /// } |
| 73 | + /// ``` |
| 74 | + PreferIncludes(tsgolint), |
| 75 | + typescript, |
| 76 | + pedantic, |
| 77 | + pending, |
| 78 | +); |
| 79 | + |
| 80 | +impl Rule for PreferIncludes {} |
0 commit comments