├── .gitignore ├── .npmignore ├── lib ├── type.js └── helpers │ └── call-expression.js ├── test ├── rules │ ├── from-map.mjs │ ├── from-map-ts.mjs │ ├── prefer-flat.mjs │ ├── prefer-array-from.mjs │ ├── prefer-flat-map.mjs │ ├── avoid-reverse.mjs │ └── no-unnecessary-this-arg.mjs ├── type.mjs ├── helpers-call-expression.mjs └── helpers │ └── from-map-test-cases.mjs ├── .editorconfig ├── .github ├── workflows │ ├── test.yml │ └── release.yml └── dependabot.yml ├── eslint.config.js ├── LICENSE ├── rules ├── prefer-array-from.js ├── prefer-flat-map.js ├── avoid-reverse.js ├── prefer-flat.js ├── no-unnecessary-this-arg.js └── from-map.js ├── package.json ├── index.js └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | coverage 3 | .nyc_output 4 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | test 3 | .* 4 | coverage 5 | .nyc_output 6 | eslint.config.js 7 | -------------------------------------------------------------------------------- /lib/type.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Martin Giger 3 | * @license MIT 4 | */ 5 | 6 | export const MEMBER_EXPRESSION = "MemberExpression"; 7 | export const ARROW_FUNCTION_EXPRESSION = "ArrowFunctionExpression"; 8 | export const IDENTIFIER = "Identifier"; 9 | -------------------------------------------------------------------------------- /test/rules/from-map.mjs: -------------------------------------------------------------------------------- 1 | import test from 'ava'; 2 | import AvaRuleTester from 'eslint-ava-rule-tester'; 3 | import rule from '../../rules/from-map.js'; 4 | import testCases from "../helpers/from-map-test-cases.mjs"; 5 | 6 | const ruleTester = new AvaRuleTester(test, { 7 | languageOptions: { 8 | ecmaVersion: 2015, 9 | }, 10 | }); 11 | 12 | ruleTester.run('from-map', rule, testCases); 13 | -------------------------------------------------------------------------------- /test/type.mjs: -------------------------------------------------------------------------------- 1 | import test from 'ava'; 2 | import { 3 | ARROW_FUNCTION_EXPRESSION, 4 | MEMBER_EXPRESSION, 5 | IDENTIFIER, 6 | } from '../lib/type.js'; 7 | 8 | test('Arrow function expression', (t) => { 9 | t.is(ARROW_FUNCTION_EXPRESSION, "ArrowFunctionExpression"); 10 | }); 11 | 12 | test('Member expression', (t) => { 13 | t.is(MEMBER_EXPRESSION, "MemberExpression"); 14 | }); 15 | 16 | test('Identifier', (t) => { 17 | t.is(IDENTIFIER, "Identifier"); 18 | }); 19 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome: http://EditorConfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | end_of_line = lf 7 | insert_final_newline = true 8 | trim_trailing_whitespace = true 9 | charset = utf-8 10 | indent_style = space 11 | indent_size = 4 12 | # C-style doc comments for eclint 13 | block_comment_start = /* 14 | block_comment = * 15 | block_comment_end = */ 16 | 17 | [{package.json,*.yml,package-lock.json,.all-contributorsrc,README.md}] 18 | indent_style = space 19 | indent_size = 2 20 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: test 2 | on: [push, pull_request] 3 | jobs: 4 | test: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - uses: actions/checkout@v6 8 | - uses: actions/setup-node@v6 9 | with: 10 | node-version: 'lts/*' 11 | cache: 'npm' 12 | - run: npm ci --no-audit 13 | - run: npm test 14 | - run: npm run coverage 15 | - uses: codecov/codecov-action@v5 16 | with: 17 | token: ${{ secrets.CODECOV_TOKEN }} 18 | -------------------------------------------------------------------------------- /lib/helpers/call-expression.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Martin Giger 3 | * @license MIT 4 | */ 5 | import { 6 | MEMBER_EXPRESSION, 7 | IDENTIFIER 8 | } from "../type.js"; 9 | 10 | // Helper functions for call expression nodes. 11 | 12 | export const isMethod = (node, name) => "callee" in node && node.callee.type === MEMBER_EXPRESSION && node.callee.property.name === name; 13 | 14 | export const isOnObject = (node, name) => "object" in node.callee && node.callee.object.type === IDENTIFIER && node.callee.object.name === name; 15 | -------------------------------------------------------------------------------- /test/rules/from-map-ts.mjs: -------------------------------------------------------------------------------- 1 | import AvaRuleTester from "eslint-ava-rule-tester"; 2 | import test from "ava"; 3 | import rule from "../../rules/from-map.js"; 4 | import testCases from '../helpers/from-map-test-cases.mjs'; 5 | import typescriptParser from "@typescript-eslint/parser"; 6 | 7 | const ruleTester = new AvaRuleTester(test, { 8 | languageOptions: { 9 | parser: typescriptParser, 10 | ecmaVersion: 2020, 11 | sourceType: 'module', 12 | }, 13 | }); 14 | 15 | ruleTester.run('from-map', rule, testCases); 16 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "npm" 4 | directory: "/" 5 | schedule: 6 | interval: "weekly" 7 | commit-message: 8 | prefix: "chore:" 9 | open-pull-requests-limit: 5 10 | versioning-strategy: "increase" 11 | groups: 12 | eslint-configs: 13 | dependency-type: "development" 14 | patterns: 15 | - "@freaktechnik/eslint-config*" 16 | - package-ecosystem: "github-actions" 17 | directory: "/" 18 | schedule: 19 | interval: "weekly" 20 | commit-message: 21 | prefix: "chore:" 22 | -------------------------------------------------------------------------------- /eslint.config.js: -------------------------------------------------------------------------------- 1 | import freaktechnikConfigNode from "@freaktechnik/eslint-config-node"; 2 | import freaktechnikConfigTest from "@freaktechnik/eslint-config-test"; 3 | import eslintPlugin from "eslint-plugin-eslint-plugin"; 4 | 5 | export default [ 6 | ...freaktechnikConfigNode, 7 | ...freaktechnikConfigTest, 8 | { 9 | files: [ "**" ], 10 | rules: { 11 | "unicorn/prefer-module": "off", 12 | }, 13 | }, 14 | { 15 | files: ["rules/*.js"], 16 | ...eslintPlugin.configs["rules-recommended"], 17 | }, 18 | { 19 | files: [ "test/rules/*.mjs" ], 20 | ...eslintPlugin.configs["tests-recommended"], 21 | }, 22 | ]; 23 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | on: 3 | push: 4 | tags: 5 | - 'v[0-9]+\.[0-9]+\.[0-9]+' 6 | jobs: 7 | test: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v6 11 | - uses: actions/setup-node@v6 12 | with: 13 | node-version: 'lts/*' 14 | check-latest: true 15 | cache: 'npm' 16 | - run: npm i -g npm@latest 17 | - run: npm ci --no-audit 18 | - run: npm t 19 | npm-publish: 20 | needs: test 21 | runs-on: ubuntu-latest 22 | name: Publish 23 | permissions: 24 | id-token: write 25 | environment: 26 | name: production 27 | url: https://www.npmjs.com/package/eslint-plugin-array-func 28 | steps: 29 | - uses: actions/checkout@v6 30 | - uses: actions/setup-node@v6 31 | with: 32 | node-version: 'lts/*' 33 | check-latest: true 34 | cache: 'npm' 35 | - run: npm i -g npm@latest 36 | - run: npm publish 37 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2017 Martin Giger 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /test/rules/prefer-flat.mjs: -------------------------------------------------------------------------------- 1 | import test from 'ava'; 2 | import AvaRuleTester from 'eslint-ava-rule-tester'; 3 | import rule from '../../rules/prefer-flat.js'; 4 | 5 | const ruleTester = new AvaRuleTester(test, { 6 | languageOptions: { 7 | ecmaVersion: 2018, 8 | }, 9 | }); 10 | 11 | ruleTester.run('prefer-flat', rule, { 12 | valid: [ 13 | 'array.flat()', 14 | 'array.reduce((p, n) => n.concat(p), [])', 15 | 'array.reduce((p, n) => n + p, 0)', 16 | 'array.reduce((p, []) => p.concat({}), [])', 17 | 'array.reduce((p, n) => p.concat(n), [1])', 18 | 'array.reduce((p, n) => p.concat(n))', 19 | 'array.reduce((p, n) => p.concat(n, n), [])', 20 | ], 21 | invalid: [ 22 | { 23 | code: '[].concat(...array)', 24 | errors: [ { 25 | messageId: 'preferFlat', 26 | column: 1, 27 | line: 1, 28 | } ], 29 | output: 'array.flat()', 30 | }, 31 | { 32 | code: 'array.reduce((p, n) => p.concat(n), [])', 33 | errors: [ { 34 | messageId: 'preferFlat', 35 | column: 1, 36 | line: 1, 37 | } ], 38 | output: 'array.flat()', 39 | }, 40 | ], 41 | }); 42 | -------------------------------------------------------------------------------- /rules/prefer-array-from.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @license MIT 3 | * @author Martin Giger 4 | */ 5 | 6 | const firstElement = (array) => { 7 | const [ element ] = array; 8 | return element; 9 | }; 10 | 11 | export default { 12 | meta: { 13 | docs: { 14 | description: "Prefer using Array.from over spreading an iterable in an array literal. Using Array.from also preserves the original type of TypedArrays while mapping.", 15 | recommended: true, 16 | }, 17 | schema: [], 18 | fixable: "code", 19 | type: "problem", 20 | messages: { 21 | preferArrayFrom: "Use Array.from to convert from iterable to array", 22 | }, 23 | }, 24 | create(context) { 25 | return { 26 | "ArrayExpression > SpreadElement:first-child:last-child"(node) { 27 | node = node.parent; 28 | context.report({ 29 | node, 30 | messageId: 'preferArrayFrom', 31 | fix(fixer) { 32 | const { sourceCode } = context; 33 | return fixer.replaceText(node, `Array.from(${sourceCode.getText(firstElement(node.elements).argument)})`); 34 | }, 35 | }); 36 | }, 37 | }; 38 | }, 39 | }; 40 | -------------------------------------------------------------------------------- /test/rules/prefer-array-from.mjs: -------------------------------------------------------------------------------- 1 | import test from 'ava'; 2 | import AvaRuleTester from 'eslint-ava-rule-tester'; 3 | import rule from '../../rules/prefer-array-from.js'; 4 | 5 | const ruleTester = new AvaRuleTester(test, { 6 | languageOptions: { 7 | ecmaVersion: 2015, 8 | }, 9 | }); 10 | 11 | ruleTester.run('perfer-array-from', rule, { 12 | valid: [ 13 | 'Array.from(new Set())', 14 | 'Array.from(iterable)', 15 | '[1, ...iterable]', 16 | '[1, 2, 3]', 17 | '[iterable]', 18 | ], 19 | invalid: [ 20 | { 21 | code: '[...iterable]', 22 | errors: [ { 23 | messageId: "preferArrayFrom", 24 | column: 1, 25 | line: 1, 26 | } ], 27 | output: 'Array.from(iterable)', 28 | }, 29 | { 30 | code: '[...[1, 2]]', 31 | errors: [ { 32 | messageId: "preferArrayFrom", 33 | column: 1, 34 | line: 1, 35 | } ], 36 | output: 'Array.from([1, 2])', 37 | }, 38 | { 39 | code: '[..."test"]', 40 | errors: [ { 41 | messageId: "preferArrayFrom", 42 | column: 1, 43 | line: 1, 44 | } ], 45 | output: 'Array.from("test")', 46 | }, 47 | ], 48 | }); 49 | -------------------------------------------------------------------------------- /test/rules/prefer-flat-map.mjs: -------------------------------------------------------------------------------- 1 | import test from 'ava'; 2 | import AvaRuleTester from 'eslint-ava-rule-tester'; 3 | import rule from '../../rules/prefer-flat-map.js'; 4 | 5 | const ruleTester = new AvaRuleTester(test, { 6 | languageOptions: { 7 | ecmaVersion: 2018, 8 | }, 9 | }); 10 | 11 | ruleTester.run('prefer-flat-map', rule, { 12 | valid: [ 13 | 'array.flatMap((m) => m)', 14 | 'array.flat()', 15 | 'array.map((r) => r + 1)', 16 | 'array.flat().map((r) => r + 1)', 17 | 'array.map((r) => r + 1).reverse().flat()', 18 | 'array.map((p) => p).flat(99)', 19 | ], 20 | invalid: [ 21 | { 22 | code: 'array.map((p) => p).flat()', 23 | errors: [ { 24 | messageId: 'preferFlatMap', 25 | column: 7, 26 | line: 1, 27 | } ], 28 | output: 'array.flatMap((p) => p)', 29 | }, 30 | { 31 | code: 'foo(); array.map((p) => p).flat(); test();', 32 | errors: [ { 33 | messageId: 'preferFlatMap', 34 | column: 14, 35 | line: 1, 36 | } ], 37 | output: 'foo(); array.flatMap((p) => p); test();', 38 | }, 39 | { 40 | code: 'array.map((r) => r).flat(1)', 41 | errors: [ { 42 | messageId: 'preferFlatMap', 43 | column: 7, 44 | line: 1, 45 | } ], 46 | output: 'array.flatMap((r) => r)', 47 | }, 48 | ], 49 | }); 50 | -------------------------------------------------------------------------------- /test/rules/avoid-reverse.mjs: -------------------------------------------------------------------------------- 1 | import test from 'ava'; 2 | import AvaRuleTester from 'eslint-ava-rule-tester'; 3 | import rule from '../../rules/avoid-reverse.js'; 4 | 5 | const ruleTester = new AvaRuleTester(test, { 6 | languageOptions: { 7 | ecmaVersion: 2015, 8 | }, 9 | }); 10 | 11 | ruleTester.run('avoid-reverse', rule, { 12 | valid: [ 13 | 'array.lastIndexOf(1)', 14 | 'array.indexOf(1)', 15 | 'array.reduce((p, c) => p + c, 0)', 16 | 'array.reduceRight((p, c) => p + c, 0)', 17 | 'array.reverse()', 18 | 'array.reverse().map((r) => r + 1)', 19 | ], 20 | invalid: [ 21 | { 22 | code: 'array.reverse().reduce((p, c) => p + c, 0)', 23 | errors: [ { 24 | messageId: 'avoidReverse', 25 | column: 7, 26 | line: 1, 27 | data: { 28 | reversed: 'reduceRight', 29 | methodName: 'reduce', 30 | }, 31 | } ], 32 | output: 'array.reduceRight((p, c) => p + c, 0)', 33 | }, 34 | { 35 | code: 'array.reverse().reduceRight((p, c) => p + c, 0)', 36 | errors: [ { 37 | messageId: 'avoidReverse', 38 | column: 7, 39 | line: 1, 40 | data: { 41 | reversed: 'reduce', 42 | methodName: 'reduceRight', 43 | }, 44 | } ], 45 | output: 'array.reduce((p, c) => p + c, 0)', 46 | }, 47 | ], 48 | }); 49 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "eslint-plugin-array-func", 3 | "version": "5.1.0", 4 | "description": "Rules dealing with Array functions and methods.", 5 | "main": "index.js", 6 | "scripts": { 7 | "lint:js": "eslint index.js package.json rules/ test/", 8 | "lint": "npm run lint:js", 9 | "test": "npm run lint && c8 ava", 10 | "coverage": "c8 report -r lcov" 11 | }, 12 | "author": "Martin Giger (https://humanoids.be)", 13 | "license": "MIT", 14 | "devDependencies": { 15 | "@freaktechnik/eslint-config-node": "^12.0.1", 16 | "@freaktechnik/eslint-config-test": "^12.0.1", 17 | "@typescript-eslint/parser": "^8.48.1", 18 | "ava": "^6.4.1", 19 | "c8": "^10.1.3", 20 | "eslint": "^9.39.1", 21 | "eslint-ava-rule-tester": "^5.0.1", 22 | "eslint-plugin-eslint-plugin": "^7.2.0", 23 | "eslint-plugin-optimize-regex": "^1.2.1", 24 | "typescript": "^5.9.3" 25 | }, 26 | "peerDependencies": { 27 | "eslint": ">=8.51.0" 28 | }, 29 | "keywords": [ 30 | "eslint", 31 | "eslintplugin" 32 | ], 33 | "nyc": { 34 | "reporter": [ 35 | "lcov", 36 | "text" 37 | ] 38 | }, 39 | "engines": { 40 | "node": "^12.22.0 || ^14.17.0 || >=16.0.0" 41 | }, 42 | "repository": { 43 | "type": "git", 44 | "url": "git+https://github.com/freaktechnik/eslint-plugin-array-func.git" 45 | }, 46 | "bugs": { 47 | "url": "https://github.com/freaktechnik/eslint-plugin-array-func/issues" 48 | }, 49 | "ava": { 50 | "files": [ 51 | "test/**/*", 52 | "!test/helpers" 53 | ] 54 | }, 55 | "publishConfig": { 56 | "provenance": true 57 | }, 58 | "type": "module" 59 | } 60 | -------------------------------------------------------------------------------- /test/helpers-call-expression.mjs: -------------------------------------------------------------------------------- 1 | import test from 'ava'; 2 | import { 3 | isMethod, isOnObject, 4 | } from '../lib/helpers/call-expression.js'; 5 | import { 6 | MEMBER_EXPRESSION, IDENTIFIER, 7 | } from '../lib/type.js'; 8 | 9 | test('is method', (t) => { 10 | const name = "test"; 11 | t.true(isMethod({ 12 | callee: { 13 | type: MEMBER_EXPRESSION, 14 | property: { 15 | name, 16 | }, 17 | }, 18 | }, name)); 19 | }); 20 | 21 | test('not is method', (t) => { 22 | const name = 'test'; 23 | t.false(isMethod({}, name)); 24 | t.false(isMethod({ 25 | callee: { 26 | type: IDENTIFIER, 27 | property: { 28 | name, 29 | }, 30 | }, 31 | }, name)); 32 | t.false(isMethod({ 33 | callee: { 34 | type: MEMBER_EXPRESSION, 35 | property: { 36 | name: 'foo', 37 | }, 38 | }, 39 | })); 40 | }); 41 | 42 | test('is on object', (t) => { 43 | const name = 'test'; 44 | t.true(isOnObject({ 45 | callee: { 46 | object: { 47 | type: IDENTIFIER, 48 | name, 49 | }, 50 | }, 51 | }, name)); 52 | }); 53 | 54 | test('is not on object', (t) => { 55 | const name = 'test'; 56 | t.false(isOnObject({ 57 | callee: {}, 58 | }, name)); 59 | t.false(isOnObject({ 60 | callee: { 61 | type: MEMBER_EXPRESSION, 62 | name, 63 | }, 64 | }, name)); 65 | t.false(isOnObject({ 66 | callee: { 67 | type: IDENTIFIER, 68 | name: 'foo', 69 | }, 70 | }, name)); 71 | }); 72 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @license MIT 3 | * @author Martin Giger 4 | */ 5 | import fromMap from "./rules/from-map.js"; 6 | import noUnnecessaryThisArgument from "./rules/no-unnecessary-this-arg.js"; 7 | import preferArrayFrom from "./rules/prefer-array-from.js"; 8 | import avoidReverse from "./rules/avoid-reverse.js"; 9 | import preferFlatMap from "./rules/prefer-flat-map.js"; 10 | import preferFlat from "./rules/prefer-flat.js"; 11 | 12 | const index = { 13 | meta: { 14 | name: "eslint-plugin-array-func", 15 | version: "5.0.1", 16 | namespace: "array-func", 17 | }, 18 | rules: { 19 | "from-map": fromMap, 20 | "no-unnecessary-this-arg": noUnnecessaryThisArgument, 21 | "prefer-array-from": preferArrayFrom, 22 | "avoid-reverse": avoidReverse, 23 | "prefer-flat-map": preferFlatMap, 24 | "prefer-flat": preferFlat, 25 | }, 26 | configs: {}, 27 | }; 28 | index.configs.recommended = { 29 | name: 'array-func/recommended', 30 | plugins: { "array-func": index }, 31 | rules: { 32 | "array-func/from-map": "error", 33 | "array-func/no-unnecessary-this-arg": "error", 34 | "array-func/prefer-array-from": "error", 35 | "array-func/avoid-reverse": "error", 36 | }, 37 | }; 38 | index.configs.all = { 39 | name: 'array-func/all', 40 | plugins: { "array-func": index }, 41 | rules: { 42 | "array-func/from-map": "error", 43 | "array-func/no-unnecessary-this-arg": "error", 44 | "array-func/prefer-array-from": "error", 45 | "array-func/avoid-reverse": "error", 46 | "array-func/prefer-flat-map": "error", 47 | "array-func/prefer-flat": "error", 48 | }, 49 | }; 50 | 51 | export default index; 52 | -------------------------------------------------------------------------------- /rules/prefer-flat-map.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @license MIT 3 | * @author Martin Giger 4 | */ 5 | 6 | export default { 7 | meta: { 8 | docs: { 9 | description: "Prefer using the flatMap over an immediate .flat() call after a .map().", 10 | recommended: true, 11 | }, 12 | fixable: "code", 13 | schema: [], 14 | type: "suggestion", 15 | messages: { 16 | preferFlatMap: "Use flatMap instead of .map().flat()", 17 | }, 18 | }, 19 | create(context) { 20 | return { 21 | 'CallExpression[callee.type="MemberExpression"]:matches([arguments.length=0],[arguments.0.type="Literal"][arguments.0.value=1]) > MemberExpression[property.name="flat"] > CallExpression[callee.type="MemberExpression"][callee.property.name="map"]'(node) { 22 | const callee = node.parent.parent; 23 | 24 | context.report({ 25 | node: callee.property, 26 | loc: { 27 | start: node.callee.property.loc.start, 28 | end: callee.loc.end, 29 | }, 30 | messageId: "preferFlatMap", 31 | fix(fixer) { 32 | const [ 33 | , endOfMap, 34 | ] = node.range, 35 | [ 36 | , endOfFlat, 37 | ] = callee.range; 38 | return [ 39 | fixer.replaceTextRange(node.callee.property.range, 'flatMap'), 40 | fixer.removeRange([ 41 | endOfMap, 42 | endOfFlat, 43 | ]), 44 | ]; 45 | }, 46 | }); 47 | }, 48 | }; 49 | }, 50 | }; 51 | -------------------------------------------------------------------------------- /test/rules/no-unnecessary-this-arg.mjs: -------------------------------------------------------------------------------- 1 | import test from 'ava'; 2 | import AvaRuleTester from 'eslint-ava-rule-tester'; 3 | import rule from '../../rules/no-unnecessary-this-arg.js'; 4 | 5 | const ruleTester = new AvaRuleTester(test, { 6 | languageOptions: { 7 | ecmaVersion: 2015, 8 | }, 9 | }); 10 | 11 | ruleTester.run('no-unnecessary-this-arg', rule, { 12 | valid: [ 13 | 'array.map((t) => t.id)', 14 | 'array.some((t) => t !== "a")', 15 | 'Array.from(iterable, (t) => t.id)', 16 | 'array.map(function(t) { return t.id; }, b)', 17 | 'Array.from(iterable, function(t) { return t.id; }, b)', 18 | 'array.filter(this.isGood, this)', 19 | ], 20 | invalid: [ 21 | { 22 | code: 'Array.from(iterable, (t) => t.id, b)', 23 | errors: [ { 24 | messageId: "unnecessaryThisArgStatic", 25 | column: 35, 26 | line: 1, 27 | } ], 28 | output: 'Array.from(iterable, (t) => t.id)', 29 | }, 30 | { 31 | code: 'array.map((t) => t.id, a)', 32 | errors: [ { 33 | messageId: "unnecessaryThisArgMethod", 34 | column: 24, 35 | line: 1, 36 | } ], 37 | output: null, 38 | }, 39 | { 40 | code: 'array.some((t) => t.id, b)', 41 | errors: [ { 42 | messageId: "unnecessaryThisArgMethod", 43 | column: 25, 44 | line: 1, 45 | } ], 46 | output: null, 47 | }, 48 | { 49 | code: 'array.filter((t) => t.id, 2)', 50 | errors: [ { 51 | messageId: "unnecessaryThisArgMethod", 52 | column: 27, 53 | line: 1, 54 | } ], 55 | output: null, 56 | }, 57 | { 58 | code: 'array.filter((t) => t.id, null)', 59 | errors: [ { 60 | messageId: "unnecessaryThisArgMethod", 61 | column: 27, 62 | line: 1, 63 | } ], 64 | output: null, 65 | }, 66 | ], 67 | }); 68 | -------------------------------------------------------------------------------- /rules/avoid-reverse.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @license MIT 3 | * @author Martin Giger 4 | */ 5 | import { isMethod } from "../lib/helpers/call-expression.js"; 6 | 7 | const REPLACEMENTS = { 8 | reduce: "reduceRight", 9 | reduceRight: "reduce", 10 | }; 11 | 12 | export default { 13 | meta: { 14 | docs: { 15 | description: "Prefer methods operating from the right over reversing the array", 16 | recommended: true, 17 | }, 18 | schema: [], 19 | fixable: "code", 20 | type: "suggestion", 21 | messages: { 22 | avoidReverse: "Prefer using {{ reversed }} over reversing the array and {{ methodName }}", 23 | }, 24 | }, 25 | create(context) { 26 | return { 27 | 'CallExpression[callee.type="MemberExpression"] > MemberExpression > CallExpression[callee.property.name="reverse"]'(node) { 28 | const parent = node; 29 | node = parent.parent.parent; 30 | if(Object.keys(REPLACEMENTS).every((m) => !isMethod(node, m))) { 31 | return; 32 | } 33 | const reversed = REPLACEMENTS[node.callee.property.name]; 34 | 35 | context.report({ 36 | node: node.callee.property, 37 | loc: { 38 | start: parent.callee.property.loc.start, 39 | end: node.callee.property.loc.end, 40 | }, 41 | messageId: "avoidReverse", 42 | data: { 43 | reversed, 44 | methodName: node.callee.property.name, 45 | }, 46 | fix(fixer) { 47 | const [ propertyStart ] = parent.callee.property.range, 48 | [ 49 | , propertyEnd, 50 | ] = node.callee.property.range; 51 | return fixer.replaceTextRange([ 52 | propertyStart, 53 | propertyEnd, 54 | ], reversed); 55 | }, 56 | }); 57 | }, 58 | }; 59 | }, 60 | }; 61 | -------------------------------------------------------------------------------- /rules/prefer-flat.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @license MIT 3 | * @author Martin Giger 4 | */ 5 | 6 | const 7 | firstElement = ([ first ]) => first, 8 | secondElement = ([ 9 | , second, 10 | ]) => second; 11 | 12 | export default { 13 | meta: { 14 | docs: { 15 | description: "Prefer using .flat() over concatenating to flatten an array.", 16 | recommended: true, 17 | }, 18 | schema: [], 19 | fixable: "code", 20 | type: "suggestion", 21 | messages: { 22 | preferFlat: "Use flat to flatten an array", 23 | }, 24 | }, 25 | create(context) { 26 | return { 27 | 'CallExpression[callee.type="MemberExpression"][callee.property.name="concat"][callee.object.type="ArrayExpression"][callee.object.elements.length=0] > SpreadElement'(node) { 28 | node = node.parent; 29 | context.report({ 30 | node, 31 | messageId: "preferFlat", 32 | fix(fixer) { 33 | const { sourceCode } = context; 34 | //TODO could be an iterable, so Array.from may be needed. 35 | return fixer.replaceText(node, `${sourceCode.getText(firstElement(node.arguments).argument)}.flat()`); 36 | }, 37 | }); 38 | }, 39 | // eslint-disable-next-line no-secrets/no-secrets 40 | 'CallExpression[callee.type="MemberExpression"][callee.property.name="reduce"][arguments.length=2][arguments.1.type=ArrayExpression][arguments.1.elements.length=0] > *:function[params.length=2][params.0.type=Identifier][params.1.type=Identifier] > CallExpression[callee.type="MemberExpression"][callee.property.name="concat"][arguments.length=1][arguments.0.type=Identifier]'(node) { 41 | const reduceCallbackParameters = node.parent.params; 42 | 43 | // arr.reducer((a, b) => a.concat(b), []) 44 | // "concat" function must be called on "a" and concat argument must be "b". 45 | if( 46 | firstElement(node.arguments).name === secondElement(reduceCallbackParameters).name && 47 | node.callee.object.name === firstElement(reduceCallbackParameters).name 48 | ) { 49 | context.report({ 50 | node: node.parent.parent, 51 | messageId: "preferFlat", 52 | fix(fixer) { 53 | const { sourceCode } = context; 54 | return fixer.replaceText(node.parent.parent, `${sourceCode.getText(node.parent.parent.callee.object)}.flat()`); 55 | }, 56 | }); 57 | } 58 | }, 59 | }; 60 | }, 61 | }; 62 | -------------------------------------------------------------------------------- /test/helpers/from-map-test-cases.mjs: -------------------------------------------------------------------------------- 1 | export default { 2 | valid: [ 3 | 'array.map((t) => t.id)', 4 | 'Array.from(iterable).some((t) => t !== "a")', 5 | 'Array.from(iterable, (t) => t.id)', 6 | 'Array.from(iterable, callback)', 7 | 'Array.from(iterable).map((u, i, a) => a[i])', 8 | 'Array.from(iterable).map(callback)', 9 | 'Array.from(iterable).map((...args) => args)', 10 | ], 11 | invalid: [ 12 | { 13 | code: 'Array.from(iterable).map((t) => t.id)', 14 | errors: [ { 15 | messageId: 'useMapCb', 16 | column: 1, 17 | line: 1, 18 | } ], 19 | output: 'Array.from(iterable, (t) => t.id)', 20 | }, 21 | { 22 | code: 'Array.from(iterable, (t) => t.id, a).map((t) => t[0], b)', 23 | errors: [ { 24 | messageId: 'useMapCb', 25 | column: 1, 26 | line: 1, 27 | } ], 28 | output: 'Array.from(iterable, (t) => ((t) => t[0])(((t) => t.id)(t)), a)', 29 | }, 30 | { 31 | code: 'Array.from(iterable, function(t) { return t.id; }, a).map((t) => t[0])', 32 | errors: [ { 33 | messageId: 'useMapCb', 34 | column: 1, 35 | line: 1, 36 | } ], 37 | output: 'Array.from(iterable, function(t) { return ((t) => t[0])((function(t) { return t.id; }).call(this, t)); }, a)', 38 | }, 39 | { 40 | code: 'Array.from(iterable, function(t) { return t.id; }, a).map(function(t) { return t[0]; }, b)', 41 | errors: [ { 42 | messageId: 'useMapCb', 43 | column: 1, 44 | line: 1, 45 | } ], 46 | output: 'Array.from(iterable, function(t) { return (function(t) { return t[0]; }).call(b, (function(t) { return t.id; }).call(this, t)); }, a)', 47 | }, 48 | { 49 | code: 'Array.from(iterable, function(u) { return u.id; }, a).map(function(t, i) { return t[0]; }, b)', 50 | errors: [ { 51 | messageId: 'useMapCb', 52 | column: 1, 53 | line: 1, 54 | } ], 55 | output: 'Array.from(iterable, function(t, i) { return (function(t, i) { return t[0]; }).call(b, (function(u) { return u.id; }).call(this, t, i), i); }, a)', 56 | }, 57 | { 58 | code: 'Array.from(iterable, function(u, i) { return u.id; }, a).map(function(t) { return t[0]; }, b)', 59 | errors: [ { 60 | messageId: 'useMapCb', 61 | column: 1, 62 | line: 1, 63 | } ], 64 | output: 'Array.from(iterable, function(u, i) { return (function(t) { return t[0]; }).call(b, (function(u, i) { return u.id; }).call(this, u, i), i); }, a)', 65 | }, 66 | { 67 | code: 'Array.from(iterable, mapper).map((u, i) => u.name)', 68 | errors: [ { 69 | messageId: 'useMapCb', 70 | column: 1, 71 | line: 1, 72 | } ], 73 | output: 'Array.from(iterable, (item, index) => ((u, i) => u.name)((mapper).call(this, item, index), index))', 74 | }, 75 | { 76 | code: 'Array.from(iterable).map(getValue ? (u, i) => getValue(i) : (u, i) => i)', 77 | errors: [ { 78 | messageId: 'useMapCb', 79 | column: 1, 80 | line: 1, 81 | } ], 82 | output: 'Array.from(iterable, getValue ? (u, i) => getValue(i) : (u, i) => i)', 83 | }, 84 | ], 85 | }; 86 | -------------------------------------------------------------------------------- /rules/no-unnecessary-this-arg.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @license MIT 3 | * @author Martin Giger 4 | */ 5 | import { 6 | isMethod, 7 | isOnObject, 8 | } from "../lib/helpers/call-expression.js"; 9 | import { ARROW_FUNCTION_EXPRESSION } from "../lib/type.js"; 10 | 11 | const arrayFunctions = { 12 | from: 3, 13 | }, 14 | // All have param location 2 15 | methods = [ 16 | 'map', 17 | 'forEach', 18 | 'filter', 19 | 'find', 20 | 'findIndex', 21 | 'some', 22 | 'every', 23 | ], 24 | METHOD_ARG = 2, 25 | POS_TO_ARRAY = 1, 26 | FUNC_POS = -2, 27 | //TODO should also check if the identifier is not an arrow function expression. Similar problem to array detection. 28 | checkFunction = (node, functionName, argumentPosition) => !isMethod(node, functionName) || node.arguments.length < argumentPosition || node.arguments[argumentPosition + FUNC_POS].type !== ARROW_FUNCTION_EXPRESSION, 29 | checkArrayFunction = (functionName, parameterPosition, node, context) => { 30 | if(checkFunction(node, functionName, parameterPosition) || !isOnObject(node, "Array")) { 31 | return; 32 | } 33 | const argument = node.arguments[parameterPosition - POS_TO_ARRAY]; 34 | context.report({ 35 | node: argument, 36 | loc: argument.loc, 37 | messageId: "unnecessaryThisArgStatic", 38 | data: { 39 | name: node.callee.property.name, 40 | argument: argument.name, 41 | }, 42 | fix(fixer) { 43 | const [ 44 | , previousArgumentEnd, 45 | ] = node.arguments[parameterPosition + FUNC_POS].range, 46 | [ 47 | , argumentEnd, 48 | ] = argument.range; 49 | return fixer.removeRange([ 50 | previousArgumentEnd, 51 | argumentEnd, 52 | ]); 53 | }, 54 | }); 55 | }, 56 | checkMemberFunction = (functionName, node, context) => { 57 | //TODO somehow check if the call is on an array? 58 | if(checkFunction(node, functionName, METHOD_ARG)) { 59 | return; 60 | } 61 | const argument = node.arguments[METHOD_ARG - POS_TO_ARRAY]; 62 | context.report({ 63 | node: argument, 64 | loc: argument.loc, 65 | messageId: "unnecessaryThisArgMethod", 66 | data: { 67 | name: node.callee.property.name, 68 | argument: argument.name || argument.value || argument.raw, 69 | }, 70 | }); 71 | }; 72 | 73 | export default { 74 | meta: { 75 | docs: { 76 | description: "Avoid the this parameter when providing arrow function as callback in array functions.", 77 | recommended: true, 78 | }, 79 | schema: [], 80 | fixable: "code", 81 | type: "suggestion", 82 | messages: { 83 | unnecessaryThisArgMethod: "Unnecessary this argument '{{ argument }}' with an arrow function as callback to {{ name }}", 84 | unnecessaryThisArgStatic: "Unnecessary this argument '{{ argument }}' with arrow function as callback to Array.{{ name }}", 85 | }, 86 | }, 87 | create(context) { 88 | return { 89 | "CallExpression:exit"(node) { 90 | for(const [ 91 | functionName, 92 | functionBody, 93 | ] of Object.entries(arrayFunctions)) { 94 | checkArrayFunction(functionName, functionBody, node, context); 95 | } 96 | 97 | for(const functionName of methods) { 98 | checkMemberFunction(functionName, node, context); 99 | } 100 | }, 101 | }; 102 | }, 103 | }; 104 | -------------------------------------------------------------------------------- /rules/from-map.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @license MIT 3 | * @author Martin Giger 4 | */ 5 | import { ARROW_FUNCTION_EXPRESSION } from "../lib/type.js"; 6 | 7 | const ALL_PARAMS = [ 8 | { name: 'item' }, 9 | { name: 'index' }, 10 | ]; 11 | 12 | function isFunction(node) { 13 | return node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression"; 14 | } 15 | 16 | export default { 17 | meta: { 18 | docs: { 19 | description: "Prefer using the mapFn callback of Array.from over an immediate .map() call.", 20 | recommended: true, 21 | }, 22 | fixable: "code", 23 | type: "suggestion", 24 | schema: [], 25 | messages: { 26 | useMapCb: "Use mapFn callback of Array.from instead of map()", 27 | }, 28 | }, 29 | create(context) { 30 | return { 31 | 'CallExpression[callee.type="MemberExpression"] > MemberExpression[property.name="map"][property] > CallExpression[callee.type="MemberExpression"][callee.property.name="from"][callee.object.type="Identifier"][callee.object.name="Array"]'(node) { 32 | const parent = node, 33 | callee = node.parent, 34 | [ 35 | mapCallback, 36 | mapThisArgument, 37 | ] = callee.parent.arguments; 38 | node = callee.parent; 39 | 40 | if(mapCallback.type === "Identifier" || 41 | (isFunction(mapCallback) && ( 42 | mapCallback.params.length > ALL_PARAMS.length || 43 | mapCallback.params.some((parameter) => parameter.type === "RestElement") 44 | )) 45 | ) { 46 | return; 47 | } 48 | 49 | context.report({ 50 | node: callee.property, 51 | loc: { 52 | start: parent.callee.loc.start, 53 | end: callee.loc.end, 54 | }, 55 | messageId: "useMapCb", 56 | fix(fixer) { 57 | const HAS_CBK = 2, 58 | PARAM_SEPARATOR = ", ", 59 | FUNCTION_END = ")", 60 | { sourceCode } = context; 61 | 62 | // Merge the from and map callbacks 63 | if(parent.arguments.length >= HAS_CBK) { 64 | const OMIT_ITEM = 1, 65 | [ 66 | _, // eslint-disable-line no-unused-vars 67 | callback, 68 | thisArgument, 69 | ] = parent.arguments, 70 | parameters = callback.type === "Identifier" 71 | ? ALL_PARAMS 72 | : callback.params.length > mapCallback.params.length ? callback.params : mapCallback.params, 73 | parameterString = parameters.map((p) => p.name).join(PARAM_SEPARATOR), 74 | getCallback = (cbk, targ, ps) => { 75 | const source = `(${sourceCode.getText(cbk)})`; 76 | if(targ && cbk.type !== ARROW_FUNCTION_EXPRESSION) { 77 | return `${source}.call(${targ.name}${PARAM_SEPARATOR}${ps})`; 78 | } 79 | return `${source}(${ps})`; 80 | }, 81 | firstCallback = getCallback(callback, { name: 'this' }, parameterString); 82 | 83 | // Try to use an arrow function for the wrapping function, fall back to a function expression if a this is specified. 84 | let functionStart = `(${parameterString}) => `, 85 | functionEnd = "", 86 | restParameterString = ''; 87 | if(thisArgument && callback.type !== ARROW_FUNCTION_EXPRESSION) { 88 | functionStart = `function(${parameterString}) { return `; 89 | functionEnd = "; }"; 90 | } 91 | if(parameters.length > OMIT_ITEM) { 92 | const restParameters_ = parameters 93 | .slice(OMIT_ITEM) 94 | .map((p) => p.name); 95 | restParameterString = PARAM_SEPARATOR + restParameters_.join(PARAM_SEPARATOR); 96 | } 97 | // The original map callback from Array.from gets nested as a parameter to the callback from map. 98 | const lastCallback = getCallback(mapCallback, mapThisArgument, `${firstCallback}${restParameterString}`), 99 | [ 100 | callbackStartLocation 101 | , callbackEndLocation, 102 | ] = callback.range, 103 | [ 104 | , parentEndLocation, 105 | ] = parent.range, 106 | [ 107 | , nodeEndLocation, 108 | ] = node.range, 109 | restParameters = sourceCode.getText().slice(callbackEndLocation, parentEndLocation); 110 | return fixer.replaceTextRange([ 111 | callbackStartLocation, 112 | nodeEndLocation, 113 | ], `${functionStart}${lastCallback}${functionEnd}${restParameters}`); 114 | } 115 | 116 | // Move the map arguments to from. 117 | const [ firstArgument ] = node.arguments, 118 | [ argumentStartLocation ] = firstArgument.range, 119 | [ 120 | , parentEndLocation, 121 | ] = parent.range; 122 | return fixer.replaceTextRange([ 123 | parentEndLocation - FUNCTION_END.length, 124 | argumentStartLocation, 125 | ], PARAM_SEPARATOR); 126 | }, 127 | }); 128 | }, 129 | }; 130 | }, 131 | }; 132 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # eslint-plugin-array-func 2 | 3 | [![codecov](https://codecov.io/gh/freaktechnik/eslint-plugin-array-func/graph/badge.svg?token=FhaBIu6Ze0)](https://codecov.io/gh/freaktechnik/eslint-plugin-array-func) 4 | 5 | Rules for Array functions and methods. 6 | 7 | ## Contents 8 | 9 | - [Installation](#installation) 10 | - [Rules](#rules) 11 | - [`from-map`](#from-map) 12 | - [Examples](#examples) 13 | - [Using the rule](#using-the-rule) 14 | - [`no-unnecessary-this-arg`](#no-unnecessary-this-arg) 15 | - [Checked Functions](#checked-functions) 16 | - [Checked Methods](#checked-methods) 17 | - [Examples](#examples-1) 18 | - [Using the rule](#using-the-rule-1) 19 | - [`prefer-array-from`](#prefer-array-from) 20 | - [Examples](#examples-2) 21 | - [Using the rule](#using-the-rule-2) 22 | - [`avoid-reverse`](#avoid-reverse) 23 | - [Examples](#examples-3) 24 | - [Using the rule](#using-the-rule-3) 25 | - [`prefer-flat-map`](#prefer-flat-map) 26 | - [Examples](#examples-4) 27 | - [Using the rule](#using-the-rule-4) 28 | - [`prefer-flat`](#prefer-flat) 29 | - [Examples](#examples-5) 30 | - [Using the rule](#using-the-rule-5) 31 | - [Configurations](#configurations) 32 | - [`array-func/recommended` Configuration](#array-funcrecommended-configuration) 33 | - [Using the Configuration](#using-the-configuration) 34 | - [`array-func/all` Configuration](#array-funcall-configuration) 35 | - [Using the Configuration](#using-the-configuration-1) 36 | - [License](#license) 37 | 38 | ## Installation 39 | 40 | Install [ESLint](https://www.github.com/eslint/eslint) either locally or globally. 41 | 42 | ```sh 43 | $ npm install -D eslint 44 | ``` 45 | 46 | If you installed `ESLint` globally, you have to install the `array-func` plugin globally too. Otherwise, install it locally. 47 | 48 | ```sh 49 | $ npm install -D eslint-plugin-array-func 50 | ``` 51 | 52 | ## Rules 53 | 54 | ### `from-map` 55 | 56 | Prefer using the `mapFn` callback of `Array.from` over an immediate `.map()` call on the `Array.from` result. 57 | 58 | `Array.from` has a `mapFn` callback that lets you map the items of the iterable to an array like you would with `.map()` except that values have not yet been truncated to fit types allowed in an array. Some iterables can't be directly converted to an array and thus have to be iterated either way. In that case using the mapping callback of `Array.from` avoids an iteration. See also [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from#Description) for an explanation of the potential benefits of using the mapping callback of `Array.from` directly. 59 | 60 | This rule is auto fixable. It will produce nested function calls if you use the `Array.from` map callback and have a `.map()` call following it. 61 | 62 | #### Examples 63 | 64 | Code that triggers this rule: 65 | 66 | ```js 67 | Array.from(iterable).map((t) => t.id); 68 | 69 | Array.from(iterable, (t) => t.id).map((id) => id[0]); 70 | ``` 71 | 72 | Code that doesn't trigger this rule: 73 | 74 | ```js 75 | Array.from(iterable, (t) => t.id); 76 | 77 | Array.from(iterable, function(t) { this.format(t); }, this); 78 | 79 | const arr = Array.from(iterable); 80 | const mappedArray = arr.map((t) => t.id); 81 | ``` 82 | 83 | #### Using the rule 84 | 85 | To use this rule, your `eslint.config.js` should at least contain the following: 86 | 87 | ```js 88 | import arrayFunc from "eslint-plugin-array-func"; 89 | 90 | export default [ 91 | { 92 | plugins: { 93 | "array-func": arrayFunc 94 | }, 95 | rules: { 96 | "array-func/from-map": "error" 97 | } 98 | } 99 | ]; 100 | ``` 101 | 102 | Alternatively you can use a [configuration](#configurations) included with this plugin. 103 | 104 | ### `no-unnecessary-this-arg` 105 | 106 | Avoid the `this` parameter when providing arrow function as callback in array functions. 107 | 108 | The `this` parameter is useless when providing arrow functions, since the `this` of arrow functions can not be rebound, thus the parameter has no effect. 109 | 110 | The fix is usually to omit the parameter. The Array methods can't be auto-fixed, since the detection of array methods is not confident enough to know that the method is being called on an array. 111 | 112 | #### Checked Functions 113 | 114 | - `from` (fixable) 115 | 116 | #### Checked Methods 117 | 118 | - `every` 119 | - `filter` 120 | - `find` 121 | - `findIndex` 122 | - `forEach` 123 | - `map` 124 | - `some` 125 | 126 | #### Examples 127 | 128 | Code that triggers this rule: 129 | 130 | ```js 131 | const array = Array.from("example", (char) => char.charCodeAt(0), this); 132 | 133 | const e = array.find((char) => char === 101, this); 134 | 135 | const exampleAsArray = array.map((char) => String.fromCharCode(char), this); 136 | 137 | const eIndex = array.findIndex((char) => char === 101, this); 138 | 139 | const containsE = array.some((char) => char === 101, this); 140 | 141 | const isOnlyE = array.every((char) => char === 101, this); 142 | 143 | const onlyEs = array.filter((char) => char === 101, this); 144 | 145 | array.forEach((char) => console.log(char), this); 146 | ``` 147 | 148 | Code that doesn't trigger this rule: 149 | 150 | ```js 151 | const array = Array.from("example", (char) => char.charCodeAt(0)); 152 | const alternateArray = Array.from("example", function(char) { 153 | return char.charCodeAt(this) 154 | }, 0); 155 | 156 | const e = array.find((char) => char === 101); 157 | 158 | const exampleAsArray = array.map((char) => String.fromCharCode(char)); 159 | 160 | const eIndex = array.findIndex((char) => char === 101); 161 | 162 | const containsE = array.some((char) => char === 101); 163 | 164 | const isOnlyE = array.every((char) => char === 101); 165 | 166 | const onlyEs = array.filter(function(char) { 167 | return char === this 168 | }, 101); 169 | 170 | array.forEach(function(char) { 171 | this.log(char); 172 | }, console); 173 | 174 | array.filter(this.isGood, this); 175 | ``` 176 | 177 | #### Using the rule 178 | 179 | To use this rule, your `eslint.config.js` should at least contain the following: 180 | 181 | ```js 182 | import arrayFunc from "eslint-plugin-array-func"; 183 | 184 | export default [ 185 | { 186 | plugins: { 187 | "array-func": arrayFunc 188 | }, 189 | rules: { 190 | "array-func/no-unnecessary-this-arg": "error" 191 | } 192 | } 193 | ]; 194 | ``` 195 | 196 | Alternatively you can use a [configuration](#configurations) included with this plugin. 197 | 198 | ### `prefer-array-from` 199 | 200 | Use `Array.from` instead of `[...iterable]`. 201 | See [`from-map`](#from-map) for additional benefits `Array.from` can provide over the spread syntax. 202 | 203 | This rule is auto fixable. 204 | 205 | #### Examples 206 | 207 | Code that triggers this rule: 208 | 209 | ```js 210 | const iterable = [..."string"]; 211 | 212 | const arrayCopy = [...iterable]; 213 | ``` 214 | 215 | Code that doesn't trigger this rule: 216 | 217 | ```js 218 | const array = [1, 2, 3]; 219 | 220 | const extendedArray = [0, ...array]; 221 | 222 | const arrayCopy = Array.from(array); 223 | 224 | const characterArray = Array.from("string"); 225 | ``` 226 | 227 | #### Using the rule 228 | 229 | To use this rule, your `eslint.config.js` should at least contain the following: 230 | 231 | ```js 232 | import arrayFunc from "eslint-plugin-array-func"; 233 | 234 | export default [ 235 | { 236 | plugins: { 237 | "array-func": arrayFunc 238 | }, 239 | rules: { 240 | "array-func/prefer-array-from": "error" 241 | } 242 | } 243 | ]; 244 | ``` 245 | 246 | Alternatively you can use a [configuration](#configurations) included with this plugin. 247 | 248 | ### `avoid-reverse` 249 | 250 | Avoid reversing the array and running a method on it if there is an equivalent 251 | of the method operating on the array from the other end. 252 | 253 | There are two operations with such equivalents: `reduce` with `reduceRight`. 254 | 255 | This rule is auto fixable. 256 | 257 | #### Examples 258 | 259 | Code that triggers this rule: 260 | 261 | ```js 262 | const string = array.reverse().reduce((p, c) => p + c, ''); 263 | 264 | const reverseString = array.reverse().reduceRight((p, c) => p + c, ''); 265 | ``` 266 | 267 | Code that doesn't trigger this rule: 268 | 269 | ```js 270 | const reverseString = array.reduce((p, c) => p + c, ''); 271 | 272 | const string = array.reduceRight((p, c) => p + c, ''); 273 | 274 | const reverseArray = array.reverse(); 275 | 276 | const reverseMap = array.reverse().map((r) => r + 1); 277 | ``` 278 | 279 | #### Using the rule 280 | 281 | To use this rule, your `eslint.config.js` should at least contain the following: 282 | 283 | ```js 284 | import arrayFunc from "eslint-plugin-array-func"; 285 | 286 | export default [ 287 | { 288 | plugins: { 289 | "array-func": arrayFunc 290 | }, 291 | rules: { 292 | "array-func/avoid-reverse": "error" 293 | } 294 | } 295 | ]; 296 | ``` 297 | 298 | Alternatively you can use a [configuration](#configurations) included with this plugin. 299 | 300 | ### `prefer-flat-map` 301 | 302 | Use `.flatMap()` to map and then flatten an array instead of using `.map().flat()`. 303 | 304 | This rule is auto fixable. 305 | 306 | #### Examples 307 | 308 | Code that triggers this rule: 309 | 310 | ```js 311 | const mappedAndFlattened = array.map((p) => p).flat(); 312 | 313 | const flatWithDefaultDepth = array.map((r) => r).flat(1); 314 | ``` 315 | 316 | Code that doesn't trigger this rule: 317 | 318 | ```js 319 | const oneAction = array.flatMap((m) => m); 320 | 321 | const flattened = array.flat(); 322 | 323 | const mapped = array.map((r) => r + 1); 324 | 325 | const flattenedThenMapped = array.flat().map((r) => r + 1); 326 | 327 | const flatMappedWithExtra = array.map((r) => r + 1).reverse().flat(); 328 | 329 | const flatWithDepth = array.map((p) => p).flat(99); 330 | ``` 331 | 332 | #### Using the rule 333 | 334 | To use this rule, your `eslint.config.js` should at least contain the following: 335 | 336 | ```js 337 | import arrayFunc from "eslint-plugin-array-func"; 338 | 339 | export default [ 340 | { 341 | plugins: { 342 | "array-func": arrayFunc 343 | }, 344 | rules: { 345 | "array-func/prefer-flat-map": "error" 346 | } 347 | } 348 | ]; 349 | ``` 350 | 351 | Alternatively you can use a [configuration](#configurations) included with this plugin. 352 | 353 | ### `prefer-flat` 354 | 355 | Use `.flat()` to flatten an array of arrays. This rule currently recognizes two 356 | patterns and can replace them with a `.flat()` call: 357 | 358 | - `[].concat(...array)` 359 | - `array.reduce((p, n) => p.concat(n), [])` 360 | 361 | This rule is auto fixable. 362 | 363 | #### Examples 364 | 365 | Code that triggers this rule: 366 | 367 | ```js 368 | const concatFlat = [].concat(...array); 369 | 370 | const reduceFlat = array.reduce((p, n) => p.concat(n), []); 371 | ``` 372 | 373 | Code that doesn't trigger this rule: 374 | 375 | ```js 376 | const flattened = array.flat(); 377 | 378 | const reverseFlat = array.reduce((p, n) => n.concat(p), []); 379 | 380 | const otherReduce = array.reduce((p, n) => n + p, 0); 381 | ``` 382 | 383 | #### Using the rule 384 | 385 | To use this rule, your `eslint.config.js` should at least contain the following: 386 | 387 | ```js 388 | import arrayFunc from "eslint-plugin-array-func"; 389 | 390 | export default [ 391 | { 392 | plugins: { 393 | "array-func": arrayFunc 394 | }, 395 | rules: { 396 | "array-func/prefer-flat": "error" 397 | } 398 | } 399 | ]; 400 | ``` 401 | 402 | Alternatively you can use a [configuration](#configurations) included with this plugin. 403 | 404 | ## Configurations 405 | 406 | ### `recommended` Configuration 407 | 408 | Rule | Error level | Fixable 409 | ---- | ----------- | ------- 410 | `array-func/from-map` | Error | Yes 411 | `array-func/no-unnecessary-this-arg` | Error | Sometimes 412 | `array-func/prefer-array-from` | Error | Yes 413 | `array-func/avoid-reverse` | Error | Yes 414 | 415 | #### Using the Configuration 416 | 417 | To enable this configuration, import the plugin and add the config to your eslint config array: 418 | 419 | ```js 420 | import arrayFunc from "eslint-plugin-array-func"; 421 | 422 | export default [ 423 | arrayFunc.configs.recommended, 424 | ]; 425 | ``` 426 | 427 | ### `all` Configuration 428 | 429 | The recommended configuration does not include all rules, since some Array methods 430 | were added after ES2015. The all configuration enables all rules the plugin 431 | containsy. 432 | 433 | Rule | Error level | Fixable 434 | ---- | ----------- | ------- 435 | `array-func/from-map` | Error | Yes 436 | `array-func/no-unnecessary-this-arg` | Error | Sometimes 437 | `array-func/prefer-array-from` | Error | Yes 438 | `array-func/avoid-reverse` | Error | Yes 439 | `array-func/prefer-flat-map` | Error | Yes 440 | `array-func/prefer-flat` | Error | Yes 441 | 442 | #### Using the Configuration 443 | 444 | To enable this configuration, import the plugin and add the config to your eslint config array: 445 | 446 | ```js 447 | import arrayFunc from "eslint-plugin-array-func"; 448 | 449 | export default [ 450 | arrayFunc.configs.all, 451 | ]; 452 | ``` 453 | 454 | ## License 455 | 456 | The `array-func` plugin is licensed under the [MIT License](LICENSE). 457 | --------------------------------------------------------------------------------