From 14f7f607f66733a6e682f5f41b2de5678f4a1b64 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Mon, 11 Dec 2017 06:32:59 -0200 Subject: [PATCH] lib: add internal removeColors helper Instead of having three times the same RegExp, just use a helper. PR-URL: https://github.com/nodejs/node/pull/17615 Reviewed-By: James M Snell Reviewed-By: Matteo Collina --- lib/internal/url.js | 5 ++--- lib/internal/util.js | 7 +++++++ lib/util.js | 6 +++--- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/lib/internal/url.js b/lib/internal/url.js index caa4c3d0283a3e..b395e77b046f10 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js @@ -6,7 +6,7 @@ const { isHexTable } = require('internal/querystring'); -const { getConstructorOf } = require('internal/util'); +const { getConstructorOf, removeColors } = require('internal/util'); const errors = require('internal/errors'); const querystring = require('querystring'); @@ -181,9 +181,8 @@ class URLSearchParams { for (var i = 0; i < list.length; i += 2) output.push(`${innerInspect(list[i])} => ${innerInspect(list[i + 1])}`); - var colorRe = /\u001b\[\d\d?m/g; var length = output.reduce( - (prev, cur) => prev + cur.replace(colorRe, '').length + separator.length, + (prev, cur) => prev + removeColors(cur).length + separator.length, -separator.length ); if (length > ctx.breakLength) { diff --git a/lib/internal/util.js b/lib/internal/util.js index 9f32785fbbfe53..e4d184e117175e 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -12,6 +12,12 @@ const noCrypto = !process.versions.openssl; const experimentalWarnings = new Set(); +const colorRegExp = /\u001b\[\d\d?m/g; + +function removeColors(str) { + return str.replace(colorRegExp, ''); +} + function isError(e) { return objectToString(e) === '[object Error]' || e instanceof Error; } @@ -297,6 +303,7 @@ module.exports = { objectToString, promisify, spliceOne, + removeColors, // Symbol used to customize promisify conversion customPromisifyArgs: kCustomPromisifyArgsSymbol, diff --git a/lib/util.js b/lib/util.js index 27a9d983c6cc47..68ef730759bb06 100644 --- a/lib/util.js +++ b/lib/util.js @@ -58,7 +58,8 @@ const { getConstructorOf, isError, promisify, - join + join, + removeColors } = require('internal/util'); const inspectDefaultOptions = Object.seal({ @@ -84,7 +85,6 @@ const strEscapeSequencesRegExp = /[\x00-\x1f\x27\x5c]/; const strEscapeSequencesReplacer = /[\x00-\x1f\x27\x5c]/g; /* eslint-enable */ const keyStrRegExp = /^[a-zA-Z_][a-zA-Z_0-9]*$/; -const colorRegExp = /\u001b\[\d\d?m/g; const numberRegExp = /^(0|[1-9][0-9]*)$/; // Escaped special characters. Use empty strings to fill up unused entries. @@ -843,7 +843,7 @@ function reduceToSingleString(ctx, output, base, braces, addLn) { var length = 0; for (var i = 0; i < output.length && length <= breakLength; i++) { if (ctx.colors) { - length += output[i].replace(colorRegExp, '').length + 1; + length += removeColors(output[i]).length + 1; } else { length += output[i].length + 1; }