From 3beecce94eb06a1f3febb4789781efe11c3f7b21 Mon Sep 17 00:00:00 2001
From: Scott Nonnenberg <scott@nonnenberg.com>
Date: Thu, 25 May 2017 13:25:08 -0700
Subject: [PATCH] fetchConversation: Minimize scans across loaded messages

FREEBIE
---
 js/models/messages.js | 23 ++++++++++++++++-------
 1 file changed, 16 insertions(+), 7 deletions(-)

diff --git a/js/models/messages.js b/js/models/messages.js
index 4e8ea058d8b..dbc5e56bb4f 100644
--- a/js/models/messages.js
+++ b/js/models/messages.js
@@ -564,7 +564,11 @@
             if (typeof unreadCount !== 'number') {
                 unreadCount = 0;
             }
-            var startingLoadedUnread = this.getLoadedUnreadCount();
+
+            var startingLoadedUnread = 0;
+            if (unreadCount > 0) {
+                startingLoadedUnread = this.getLoadedUnreadCount();
+            }
             return new Promise(function(resolve) {
                 var upper;
                 if (this.length === 0) {
@@ -586,12 +590,17 @@
                 };
                 this.fetch(options).then(resolve);
             }.bind(this)).then(function() {
-                var loadedUnread = this.getLoadedUnreadCount();
-                if (startingLoadedUnread === loadedUnread) {
-                    // that fetch didn't get us any more unread. stop fetching more.
-                    return;
-                }
-                if (loadedUnread < unreadCount) {
+                if (unreadCount > 0) {
+                    if (unreadCount <= startingLoadedUnread) {
+                        return;
+                    }
+
+                    var loadedUnread = this.getLoadedUnreadCount();
+                    if (startingLoadedUnread === loadedUnread) {
+                        // that fetch didn't get us any more unread. stop fetching more.
+                        return;
+                    }
+
                     return this.fetchConversation(conversationId, limit, unreadCount);
                 }
             }.bind(this));