Hey Maciej,
I don't think this is a good solution to the problem. It'll likely be quite costly if you have more than a few pages. Actually, this is O(n) complexity as you just move over all the pages.
How to solve this problem in a different way?
* Can you mock the data coming from the server? You can mock the server response and get always x number of items/pages, so you know where the last page is.
* Binary search with cy.request() to find the last page. This is O(log n), plus the browser doesn't need to download all the resources, parse everything, build trees, render, and pain. All these operations are costly.
* Can you do some trick like going directly to /?page=99999 which will redirect you to the last page?
* Can you always find a page with a given number of pages so you know the last one? This is a solution through controlling your test data, e.g. do a database migration before your tests run.
Lastly, please don't post code as a picture, no one can easily copy it :)