Skip to content

Commit d1a98a8

Browse files
BridgeARMylesBorins
authored andcommitted
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: #24744 Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent d09e333 commit d1a98a8

File tree

1 file changed

+20
-21
lines changed

1 file changed

+20
-21
lines changed

lib/events.js

+20-21
Original file line numberDiff line numberDiff line change
@@ -103,30 +103,29 @@ EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
103103
return $getMaxListeners(this);
104104
};
105105

106-
// Returns the longest sequence of `a` that fully appears in `b`,
107-
// of length at least 3.
108-
// This is a lazy approach but should work well enough, given that stack
109-
// frames are usually unequal or otherwise appear in groups, and that
110-
// we only run this code in case of an unhandled exception.
111-
function longestSeqContainedIn(a, b) {
112-
for (var len = a.length; len >= 3; --len) {
113-
for (var i = 0; i < a.length - len; ++i) {
114-
// Attempt to find a[i:i+len] in b
115-
for (var j = 0; j < b.length - len; ++j) {
116-
let matches = true;
117-
for (var k = 0; k < len; ++k) {
118-
if (a[i + k] !== b[j + k]) {
119-
matches = false;
120-
break;
121-
}
106+
// Returns the length and line number of the first sequence of `a` that fully
107+
// appears in `b` with a length of at least 4.
108+
function identicalSequenceRange(a, b) {
109+
for (var i = 0; i < a.length - 3; i++) {
110+
// Find the first entry of b that matches the current entry of a.
111+
const pos = b.indexOf(a[i]);
112+
if (pos !== -1) {
113+
const rest = b.length - pos;
114+
if (rest > 3) {
115+
let len = 1;
116+
const maxLen = Math.min(a.length - i, rest);
117+
// Count the number of consecutive entries.
118+
while (maxLen > len && a[i + len] === b[pos + len]) {
119+
len++;
120+
}
121+
if (len > 3) {
122+
return [len, i];
122123
}
123-
if (matches)
124-
return [ len, i, j ];
125124
}
126125
}
127126
}
128127

129-
return [ 0, 0, 0 ];
128+
return [0, 0];
130129
}
131130

132131
function enhanceStackTrace(err, own) {
@@ -135,9 +134,9 @@ function enhanceStackTrace(err, own) {
135134
const errStack = err.stack.split('\n').slice(1);
136135
const ownStack = own.stack.split('\n').slice(1);
137136

138-
const [ len, off ] = longestSeqContainedIn(ownStack, errStack);
137+
const [ len, off ] = identicalSequenceRange(ownStack, errStack);
139138
if (len > 0) {
140-
ownStack.splice(off + 1, len - 1,
139+
ownStack.splice(off + 1, len - 2,
141140
' [... lines matching original stack trace ...]');
142141
}
143142
// Do this last, because it is the only operation with side effects.

0 commit comments

Comments
 (0)