Files
test-repo/scripts/build/babel-plugins/replace-array-includes-with-indexof.js
T

32 lines
940 B
JavaScript
Raw Normal View History

2018-06-21 10:29:42 +08:00
"use strict";
//
// BEFORE:
// [__something__].includes(__something__)
2018-08-02 22:19:21 -05:00
// CONSTANT_CASE.includes(__something__)
2018-06-21 10:29:42 +08:00
//
// AFTER:
// [__something__].indexOf(__something__) !== -1
2018-08-02 22:19:21 -05:00
// CONSTANT_CASE.indexOf(__something__) !== -1
2018-06-21 10:29:42 +08:00
//
module.exports = ({ types: t }) => ({
visitor: {
CallExpression(path) {
const node = path.node;
const callee = node.callee;
if (
t.isMemberExpression(callee, { computed: false }) &&
2018-08-02 22:19:21 -05:00
(t.isArrayExpression(callee.object) ||
(t.isIdentifier(callee.object) &&
2018-09-01 20:04:37 +08:00
(/^[A-Z_]+$/.test(callee.object.name) ||
// https://github.com/eemeli/yaml/blob/1005d01/src/Anchors.js#L45
callee.object.name === "names"))) &&
2018-06-21 10:29:42 +08:00
t.isIdentifier(callee.property, { name: "includes" })
) {
callee.property.name = "indexOf";
path.replaceWith(t.binaryExpression("!==", node, t.numericLiteral(-1)));
}
}
}
});