More efficient thread grouping

A nested loop made ChangeComments#getCommentThreads O(n²) in the worst
case. Use a map to convert it to O(n).

Change-Id: I39f6a462cdd23316a1b513ebf98bbd2c8f9aaec2
This commit is contained in:
Wyatt Allen 2018-04-04 22:48:39 -07:00
parent f4652c1c65
commit cdb8a43f76

View File

@ -395,14 +395,15 @@
*/
ChangeComments.prototype.getCommentThreads = function(comments) {
const threads = [];
const idThreadMap = {};
for (const comment of comments) {
// If the comment is in reply to another comment, find that comment's
// thread and append to it.
if (comment.in_reply_to) {
const thread = threads.find(thread =>
thread.comments.some(c => c.id === comment.in_reply_to));
const thread = idThreadMap[comment.in_reply_to];
if (thread) {
thread.comments.push(comment);
idThreadMap[comment.id] = thread;
continue;
}
}
@ -419,6 +420,7 @@
newThread.commentSide = comment.side;
}
threads.push(newThread);
idThreadMap[comment.id] = newThread;
}
return threads;
};