Skip to content

Commit

Permalink
refactor: use Array.prototype.at() to get last elements (#17949)
Browse files Browse the repository at this point in the history
  • Loading branch information
mdjermanovic committed Jan 4, 2024
1 parent 51f8bc8 commit df200e1
Show file tree
Hide file tree
Showing 52 changed files with 115 additions and 113 deletions.
2 changes: 1 addition & 1 deletion Makefile.js
Expand Up @@ -340,7 +340,7 @@ function getFirstCommitOfFile(filePath) {
let commits = execSilent(`git rev-list HEAD -- ${filePath}`);

commits = splitCommandResultToLines(commits);
return commits[commits.length - 1].trim();
return commits.at(-1).trim();
}

/**
Expand Down
4 changes: 2 additions & 2 deletions lib/linter/apply-disable-directives.js
Expand Up @@ -171,7 +171,7 @@ function createCommentRemoval(directives, commentToken) {
return {
description: ruleIds.length <= 2
? ruleIds.join(" or ")
: `${ruleIds.slice(0, ruleIds.length - 1).join(", ")}, or ${ruleIds[ruleIds.length - 1]}`,
: `${ruleIds.slice(0, ruleIds.length - 1).join(", ")}, or ${ruleIds.at(-1)}`,
fix: {
range,
text: " "
Expand Down Expand Up @@ -342,7 +342,7 @@ function applyDirectives(options) {
problem.suppressions = problem.suppressions.concat(suppressions);
} else {
problem.suppressions = suppressions;
usedDisableDirectives.add(disableDirectivesForProblem[disableDirectivesForProblem.length - 1]);
usedDisableDirectives.add(disableDirectivesForProblem.at(-1));
}
}

Expand Down
4 changes: 2 additions & 2 deletions lib/linter/code-path-analysis/code-path.js
Expand Up @@ -196,7 +196,7 @@ class CodePath {
if (stack.length <= 1) {
broken = true;
} else {
skippedSegment = stack[stack.length - 2][0];
skippedSegment = stack.at(-2)[0];
}
},

Expand Down Expand Up @@ -237,7 +237,7 @@ class CodePath {
* Otherwise, we just read the value and sometimes modify the
* record as we traverse.
*/
record = stack[stack.length - 1];
record = stack.at(-1);
segment = record[0];
index = record[1];

Expand Down
2 changes: 1 addition & 1 deletion lib/linter/code-path-analysis/fork-context.js
Expand Up @@ -207,7 +207,7 @@ class ForkContext {
get head() {
const list = this.segmentsList;

return list.length === 0 ? [] : list[list.length - 1];
return list.length === 0 ? [] : list.at(-1);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion lib/linter/report-translator.js
Expand Up @@ -160,7 +160,7 @@ function mergeFixes(fixes, sourceCode) {

const originalText = sourceCode.text;
const start = fixes[0].range[0];
const end = fixes[fixes.length - 1].range[1];
const end = fixes.at(-1).range[1];
let text = "";
let lastPos = Number.MIN_SAFE_INTEGER;

Expand Down
2 changes: 1 addition & 1 deletion lib/rules/array-bracket-spacing.js
Expand Up @@ -199,7 +199,7 @@ module.exports = {
: sourceCode.getLastToken(node),
penultimate = sourceCode.getTokenBefore(last),
firstElement = node.elements[0],
lastElement = node.elements[node.elements.length - 1];
lastElement = node.elements.at(-1);

const openingBracketMustBeSpaced =
options.objectsInArraysException && isObjectType(firstElement) ||
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/block-scoped-var.js
Expand Up @@ -79,7 +79,7 @@ module.exports = {
}

// Defines a predicate to check whether or not a given reference is outside of valid scope.
const scopeRange = stack[stack.length - 1];
const scopeRange = stack.at(-1);

/**
* Check if a reference is out of scope
Expand Down
4 changes: 2 additions & 2 deletions lib/rules/callback-return.js
Expand Up @@ -147,7 +147,7 @@ module.exports = {
if (closestBlock.type === "BlockStatement") {

// find the last item in the block
const lastItem = closestBlock.body[closestBlock.body.length - 1];
const lastItem = closestBlock.body.at(-1);

// if the callback is the last thing in a block that might be ok
if (isCallbackExpression(node, lastItem)) {
Expand All @@ -168,7 +168,7 @@ module.exports = {
if (lastItem.type === "ReturnStatement") {

// but only if the callback is immediately before
if (isCallbackExpression(node, closestBlock.body[closestBlock.body.length - 2])) {
if (isCallbackExpression(node, closestBlock.body.at(-2))) {
return;
}
}
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/comma-dangle.js
Expand Up @@ -154,7 +154,7 @@ module.exports = {
* @returns {any} The last element
*/
function last(array) {
return array[array.length - 1];
return array.at(-1);
}

switch (node.type) {
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/comma-style.js
Expand Up @@ -218,7 +218,7 @@ module.exports = {

previousItemToken = tokenAfterItem
? sourceCode.getTokenBefore(tokenAfterItem)
: sourceCode.ast.tokens[sourceCode.ast.tokens.length - 1];
: sourceCode.ast.tokens.at(-1);
} else {
previousItemToken = currentItemToken;
}
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/constructor-super.js
Expand Up @@ -109,7 +109,7 @@ function isPossibleConstructor(node) {
);

case "SequenceExpression": {
const lastExpression = node.expressions[node.expressions.length - 1];
const lastExpression = node.expressions.at(-1);

return isPossibleConstructor(lastExpression);
}
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/default-case.js
Expand Up @@ -54,7 +54,7 @@ module.exports = {
* @returns {any} Last element
*/
function last(collection) {
return collection[collection.length - 1];
return collection.at(-1);
}

//--------------------------------------------------------------------------
Expand Down
4 changes: 2 additions & 2 deletions lib/rules/eol-last.js
Expand Up @@ -45,7 +45,7 @@ module.exports = {
Program: function checkBadEOF(node) {
const sourceCode = context.sourceCode,
src = sourceCode.getText(),
lastLine = sourceCode.lines[sourceCode.lines.length - 1],
lastLine = sourceCode.lines.at(-1),
location = {
column: lastLine.length,
line: sourceCode.lines.length
Expand Down Expand Up @@ -89,7 +89,7 @@ module.exports = {
});
} else if (mode === "never" && endsWithNewline) {

const secondLastLine = sourceCode.lines[sourceCode.lines.length - 2];
const secondLastLine = sourceCode.lines.at(-2);

// File is newline-terminated, but shouldn't be
context.report({
Expand Down
4 changes: 2 additions & 2 deletions lib/rules/function-paren-newline.js
Expand Up @@ -218,7 +218,7 @@ module.exports = {
case "FunctionExpression": {
const leftParen = sourceCode.getFirstToken(node, astUtils.isOpeningParenToken);
const rightParen = node.params.length
? sourceCode.getTokenAfter(node.params[node.params.length - 1], astUtils.isClosingParenToken)
? sourceCode.getTokenAfter(node.params.at(-1), astUtils.isClosingParenToken)
: sourceCode.getTokenAfter(leftParen);

return { leftParen, rightParen };
Expand All @@ -234,7 +234,7 @@ module.exports = {
}

const rightParen = node.params.length
? sourceCode.getTokenAfter(node.params[node.params.length - 1], astUtils.isClosingParenToken)
? sourceCode.getTokenAfter(node.params.at(-1), astUtils.isClosingParenToken)
: sourceCode.getTokenAfter(firstToken);

return {
Expand Down
8 changes: 4 additions & 4 deletions lib/rules/indent-legacy.js
Expand Up @@ -789,7 +789,7 @@ module.exports = {
if (elements.length > 0) {

// Skip last block line check if last item in same line
if (elements[elements.length - 1].loc.end.line === node.loc.end.line) {
if (elements.at(-1).loc.end.line === node.loc.end.line) {
return;
}
}
Expand Down Expand Up @@ -873,7 +873,7 @@ module.exports = {
*/
function filterOutSameLineVars(node) {
return node.declarations.reduce((finalCollection, elem) => {
const lastElem = finalCollection[finalCollection.length - 1];
const lastElem = finalCollection.at(-1);

if ((elem.loc.start.line !== node.loc.start.line && !lastElem) ||
(lastElem && lastElem.loc.start.line !== elem.loc.start.line)) {
Expand All @@ -892,7 +892,7 @@ module.exports = {
function checkIndentInVariableDeclarations(node) {
const elements = filterOutSameLineVars(node);
const nodeIndent = getNodeIndent(node).goodChar;
const lastElement = elements[elements.length - 1];
const lastElement = elements.at(-1);

const elementsIndent = nodeIndent + indentSize * options.VariableDeclarator[node.kind];

Expand Down Expand Up @@ -999,7 +999,7 @@ module.exports = {
},

VariableDeclaration(node) {
if (node.declarations[node.declarations.length - 1].loc.start.line > node.declarations[0].loc.start.line) {
if (node.declarations.at(-1).loc.start.line > node.declarations[0].loc.start.line) {
checkIndentInVariableDeclarations(node);
}
},
Expand Down
6 changes: 3 additions & 3 deletions lib/rules/indent.js
Expand Up @@ -1077,7 +1077,7 @@ module.exports = {
"ObjectExpression, ObjectPattern"(node) {
const openingCurly = sourceCode.getFirstToken(node);
const closingCurly = sourceCode.getTokenAfter(
node.properties.length ? node.properties[node.properties.length - 1] : openingCurly,
node.properties.length ? node.properties.at(-1) : openingCurly,
astUtils.isClosingBraceToken
);

Expand Down Expand Up @@ -1458,7 +1458,7 @@ module.exports = {

if (node.cases.length) {
sourceCode.getTokensBetween(
node.cases[node.cases.length - 1],
node.cases.at(-1),
closingCurly,
{ includeComments: true, filter: astUtils.isCommentToken }
).forEach(token => offsets.ignoreToken(token));
Expand Down Expand Up @@ -1509,7 +1509,7 @@ module.exports = {
variableIndent = DEFAULT_VARIABLE_INDENT;
}

if (node.declarations[node.declarations.length - 1].loc.start.line > node.loc.start.line) {
if (node.declarations.at(-1).loc.start.line > node.loc.start.line) {

/*
* VariableDeclarator indentation is a bit different from other forms of indentation, in that the
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/key-spacing.js
Expand Up @@ -28,7 +28,7 @@ function containsLineTerminator(str) {
* @returns {any} Last element of arr.
*/
function last(arr) {
return arr[arr.length - 1];
return arr.at(-1);
}

/**
Expand Down
4 changes: 2 additions & 2 deletions lib/rules/lines-around-directive.js
Expand Up @@ -166,15 +166,15 @@ module.exports = {
reportError(firstDirective, "before", false);
}

const lastDirective = directives[directives.length - 1];
const lastDirective = directives.at(-1);
const statements = node.type === "Program" ? node.body : node.body.body;

/*
* Do not check after the last directive if the body only
* contains a directive prologue and isn't followed by a comment to ensure
* this rule behaves well with padded-blocks.
*/
if (lastDirective === statements[statements.length - 1] && !lastDirective.trailingComments) {
if (lastDirective === statements.at(-1) && !lastDirective.trailingComments) {
return;
}

Expand Down
4 changes: 2 additions & 2 deletions lib/rules/max-len.js
Expand Up @@ -124,7 +124,7 @@ module.exports = {
}

// The options object must be the last option specified…
const options = Object.assign({}, context.options[context.options.length - 1]);
const options = Object.assign({}, context.options.at(-1));

// …but max code length…
if (typeof context.options[0] === "number") {
Expand Down Expand Up @@ -290,7 +290,7 @@ module.exports = {
if (isJSXEmptyExpressionInSingleLineContainer(containingNode)) {

// push a unique node only
if (comments[comments.length - 1] !== containingNode.parent) {
if (comments.at(-1) !== containingNode.parent) {
comments.push(containingNode.parent);
}
} else {
Expand Down
4 changes: 2 additions & 2 deletions lib/rules/max-lines.js
Expand Up @@ -148,7 +148,7 @@ module.exports = {
* If file ends with a linebreak, `sourceCode.lines` will have one extra empty line at the end.
* That isn't a real line, so we shouldn't count it.
*/
if (lines.length > 1 && lines[lines.length - 1].text === "") {
if (lines.length > 1 && lines.at(-1).text === "") {
lines.pop();
}

Expand All @@ -174,7 +174,7 @@ module.exports = {
},
end: {
line: sourceCode.lines.length,
column: sourceCode.lines[sourceCode.lines.length - 1].length
column: sourceCode.lines.at(-1).length
}
};

Expand Down
14 changes: 7 additions & 7 deletions lib/rules/multiline-comment-style.js
Expand Up @@ -113,7 +113,7 @@ module.exports = {

return /^\*\s*$/u.test(lines[0]) &&
lines.slice(1, -1).every(line => /^\s* /u.test(line)) &&
/^\s*$/u.test(lines[lines.length - 1]);
/^\s*$/u.test(lines.at(-1));
}

/**
Expand Down Expand Up @@ -272,11 +272,11 @@ module.exports = {
context.report({
loc: {
start: firstComment.loc.start,
end: commentGroup[commentGroup.length - 1].loc.end
end: commentGroup.at(-1).loc.end
},
messageId: "expectedBlock",
fix(fixer) {
const range = [firstComment.range[0], commentGroup[commentGroup.length - 1].range[1]];
const range = [firstComment.range[0], commentGroup.at(-1).range[1]];

return commentLines.some(value => value.startsWith("/"))
? null
Expand All @@ -301,7 +301,7 @@ module.exports = {
});
}

if (!/^\s*$/u.test(lines[lines.length - 1])) {
if (!/^\s*$/u.test(lines.at(-1))) {
context.report({
loc: {
start: { line: firstComment.loc.end.line, column: firstComment.loc.end.column - 2 },
Expand Down Expand Up @@ -408,12 +408,12 @@ module.exports = {
context.report({
loc: {
start: firstComment.loc.start,
end: commentGroup[commentGroup.length - 1].loc.end
end: commentGroup.at(-1).loc.end
},
messageId: "expectedBlock",
fix(fixer) {
return fixer.replaceTextRange(
[firstComment.range[0], commentGroup[commentGroup.length - 1].range[1]],
[firstComment.range[0], commentGroup.at(-1).range[1]],
convertToBlock(firstComment, commentLines)
);
}
Expand Down Expand Up @@ -459,7 +459,7 @@ module.exports = {
tokenBefore && tokenBefore.loc.end.line === comment.loc.start.line - 1 &&
tokenBefore === commentList[index - 1]
) {
commentGroups[commentGroups.length - 1].push(comment);
commentGroups.at(-1).push(comment);
} else {
commentGroups.push([comment]);
}
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/newline-after-var.js
Expand Up @@ -215,7 +215,7 @@ module.exports = {
fix(fixer) {
const linesBetween = sourceCode.getText().slice(lastToken.range[1], nextToken.range[0]).split(astUtils.LINEBREAK_MATCHER);

return fixer.replaceTextRange([lastToken.range[1], nextToken.range[0]], `${linesBetween.slice(0, -1).join("")}\n${linesBetween[linesBetween.length - 1]}`);
return fixer.replaceTextRange([lastToken.range[1], nextToken.range[0]], `${linesBetween.slice(0, -1).join("")}\n${linesBetween.at(-1)}`);
}
});
}
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/newline-before-return.js
Expand Up @@ -166,7 +166,7 @@ module.exports = {
*/
function canFix(node) {
const leadingComments = sourceCode.getCommentsBefore(node);
const lastLeadingComment = leadingComments[leadingComments.length - 1];
const lastLeadingComment = leadingComments.at(-1);
const tokenBefore = sourceCode.getTokenBefore(node);

if (leadingComments.length === 0) {
Expand Down

0 comments on commit df200e1

Please sign in to comment.