events: simplify stack compare function

This simplifies the `longestSeqContainedIn()` logic by checking for
the first identical occurance of at least three frames instead of
the longest one.
It also removes an unused argument.

PR-URL: https://github.com/nodejs/node/pull/24744
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
This commit is contained in:
Ruben Bridgewater 2018-11-18 04:25:05 +01:00
parent 35a8906964
commit a76750b49e
No known key found for this signature in database
GPG Key ID: F07496B3EB3C1762

View File

@ -103,30 +103,29 @@ EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return $getMaxListeners(this); return $getMaxListeners(this);
}; };
// Returns the longest sequence of `a` that fully appears in `b`, // Returns the length and line number of the first sequence of `a` that fully
// of length at least 3. // appears in `b` with a length of at least 4.
// This is a lazy approach but should work well enough, given that stack function identicalSequenceRange(a, b) {
// frames are usually unequal or otherwise appear in groups, and that for (var i = 0; i < a.length - 3; i++) {
// we only run this code in case of an unhandled exception. // Find the first entry of b that matches the current entry of a.
function longestSeqContainedIn(a, b) { const pos = b.indexOf(a[i]);
for (var len = a.length; len >= 3; --len) { if (pos !== -1) {
for (var i = 0; i < a.length - len; ++i) { const rest = b.length - pos;
// Attempt to find a[i:i+len] in b if (rest > 3) {
for (var j = 0; j < b.length - len; ++j) { let len = 1;
let matches = true; const maxLen = Math.min(a.length - i, rest);
for (var k = 0; k < len; ++k) { // Count the number of consecutive entries.
if (a[i + k] !== b[j + k]) { while (maxLen > len && a[i + len] === b[pos + len]) {
matches = false; len++;
break; }
} if (len > 3) {
return [len, i];
} }
if (matches)
return [ len, i, j ];
} }
} }
} }
return [ 0, 0, 0 ]; return [0, 0];
} }
function enhanceStackTrace(err, own) { function enhanceStackTrace(err, own) {
@ -135,9 +134,9 @@ function enhanceStackTrace(err, own) {
const errStack = err.stack.split('\n').slice(1); const errStack = err.stack.split('\n').slice(1);
const ownStack = own.stack.split('\n').slice(1); const ownStack = own.stack.split('\n').slice(1);
const [ len, off ] = longestSeqContainedIn(ownStack, errStack); const [ len, off ] = identicalSequenceRange(ownStack, errStack);
if (len > 0) { if (len > 0) {
ownStack.splice(off + 1, len - 1, ownStack.splice(off + 1, len - 2,
' [... lines matching original stack trace ...]'); ' [... lines matching original stack trace ...]');
} }
// Do this last, because it is the only operation with side effects. // Do this last, because it is the only operation with side effects.