Skip to content

Commit

Permalink
assert: refactor to avoid unsafe array iteration
Browse files Browse the repository at this point in the history
PR-URL: #37344
Reviewed-By: Darshan Sen <raisinten@gmail.com>
  • Loading branch information
aduh95 authored and targos committed Jun 11, 2021
1 parent f5541dd commit cfff3b4
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions lib/internal/assert/assertion_error.js
Expand Up @@ -313,6 +313,17 @@ function createErrDiff(actual, expected, operator) {
return `${msg}${skipped ? skippedMsg : ''}\n${res}${other}${end}${indicator}`;
}

function addEllipsis(string) {
const lines = StringPrototypeSplit(string, '\n', 11);
if (lines.length > 10) {
lines.length = 10;
return `${ArrayPrototypeJoin(lines, '\n')}\n...`;
} else if (string.length > 512) {
return `${StringPrototypeSlice(string, 512)}...`;
}
return string;
}

class AssertionError extends Error {
constructor(options) {
if (typeof options !== 'object' || options === null) {
Expand Down Expand Up @@ -469,16 +480,11 @@ class AssertionError extends Error {
const tmpActual = this.actual;
const tmpExpected = this.expected;

for (const name of ['actual', 'expected']) {
if (typeof this[name] === 'string') {
const lines = StringPrototypeSplit(this[name], '\n');
if (lines.length > 10) {
lines.length = 10;
this[name] = `${ArrayPrototypeJoin(lines, '\n')}\n...`;
} else if (this[name].length > 512) {
this[name] = `${StringPrototypeSlice(this[name], 512)}...`;
}
}
if (typeof this.actual === 'string') {
this.actual = addEllipsis(this.actual);
}
if (typeof this.expected === 'string') {
this.expected = addEllipsis(this.expected);
}

// This limits the `actual` and `expected` property default inspection to
Expand Down

0 comments on commit cfff3b4

Please sign in to comment.