Custom rules ESLint for using Array.push instead of direct assignment to add items to an array

Viewed 159

I want to create a custom rule to prevent giving values directly to the array, and encourage using array.push

e.g

const newArr = ['test', 'tust'];

// invalid
newArr[newArr.length - 1] = 'lorem ipsum';
newArr[newArr.length] = 'lorem ipsum 1';
newArr[0] = 'lorem ipsum 0';

// valid
newArr.push('test push');

I tried to make it like this in ast explorer but it still didn't work

"use strict";

module.exports = {
    meta: {
        type: "suggestion",

        docs: {
            description: "disallow direct assign to array",
            category: "Stylistic Issues",
        },
        schema: [],
        messages: {
            preferLiteral: "Using `array.push` insted of direct assign value to array"
        }
    },

    create(context) {
        function check(node) {
            if (
                node.parent.type === "VariableDeclarator"
            ) {
                console.log(node)
                context.report({ node, messageId: "preferLiteral" });
            }
        }

        return {
            ArrayExpression: check
        };

    }
};
0 Answers
Related