Skip to content

Commit aca5ed5

Browse files
BridgeARMylesBorins
authored andcommittedMay 16, 2019
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 ead4bb6 commit aca5ed5

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
@@ -104,30 +104,29 @@ EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
104104
return $getMaxListeners(this);
105105
};
106106

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

130-
return [ 0, 0, 0 ];
129+
return [0, 0];
131130
}
132131

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

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

0 commit comments

Comments
 (0)