From cfff3b4462ddbbc56be466b31350dad89942d2e0 Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Fri, 12 Feb 2021 12:49:51 +0100 Subject: [PATCH] assert: refactor to avoid unsafe array iteration PR-URL: https://github.com/nodejs/node/pull/37344 Reviewed-By: Darshan Sen --- lib/internal/assert/assertion_error.js | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/lib/internal/assert/assertion_error.js b/lib/internal/assert/assertion_error.js index e9e9a101970509..83e32ef2b547e2 100644 --- a/lib/internal/assert/assertion_error.js +++ b/lib/internal/assert/assertion_error.js @@ -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) { @@ -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