Skip to content

Instantly share code, notes, and snippets.

@kalda341
Created July 4, 2017 00:32
Show Gist options
  • Save kalda341/26206468c3bd51a87d2501b05241563f to your computer and use it in GitHub Desktop.
Save kalda341/26206468c3bd51a87d2501b05241563f to your computer and use it in GitHub Desktop.
// Load n more call records into a list
loadN(list, n) {
var pages = this.get('pages');
// This serves two purposes, allowing us to access the contents of the pages,
// but also preventing us from making concurrent requests and screwing up the
// ordering
return Ember.RSVP.all(pages).then(pagesData => {
// We want to be adding items from the start if we currently have no items
var addingItems = list.length == 0;
// Loop through pages while there are still pages to go through, and we
// haven't yet added the full n items. Add items to our list.
for (var pageNo=0; pageNo<pagesData.length && n; pageNo++) {
// The oldest item is the last in the list.
var oldest = list.slice(-1)[0];
var page = pagesData[pageNo];
// If posInPage is not -1 then we have found the oldest item in the
// list. In that case we should start adding items after. If it is -1
// and we are adding, then we should start adding items from position
// 0. In both of these cases we will start from posInPage + 1.
var posInPage = page.indexOf(oldest);
if (addingItems = addingItems || posInPage != -1) { // Assignment is intended
// We want to all the remaining items in the list, or n, whatever is smaller
var addingNo = Math.min(page.length - posInPage - 1, n);
list.pushObjects(page.slice(posInPage + 1, posInPage + addingNo + 1));
// We now don't need as many items
n -= addingNo;
}
}
// If we don't have enough records in our stored pages, then request
// another page
if (n) {
var proxy = this._request(n);
pages.pushObject(proxy);
// Do not resolve our current promise until the new page has loaded
// and we've added the contents
return proxy.then(data => {
list.pushObjects(data);
});
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment