Skip to content

Instantly share code, notes, and snippets.

@go-cristian
Created February 11, 2020 16:40
Show Gist options
  • Save go-cristian/db59f58b9e8a2acf49007cfa40c557c8 to your computer and use it in GitHub Desktop.
Save go-cristian/db59f58b9e8a2acf49007cfa40c557c8 to your computer and use it in GitHub Desktop.
const from = PAGE_SIZE * page
let accumulator = 0
let assigned = 0
let currentCityIndex = 0
let currentCityPage = 0
let pages: number[] = []
let results: Listing[] = []
while (assigned < PAGE_SIZE || currentCityIndex === CITIES.length - 1) {
const response = await axios.get(
URL_OTIS,
defaultConfig(types, CITIES[currentCityIndex], currentCityPage + 1)
)
const mapped = response.data.results.map(mapOtisResult)
const count = response.data.results.length
const total = response.data.count
if (from > total && results.length === 0) {
pages[currentCityIndex] = total
currentCityPage = 0
currentCityIndex++
accumulator += total
} else {
if (currentCityPage == 0) {
pages[currentCityIndex] = total
}
const currentCityMaxPage = Math.ceil(
pages[currentCityIndex] / PAGE_SIZE
)
if (currentCityPage === currentCityMaxPage) {
currentCityPage = 0
currentCityIndex++
} else {
currentCityPage++
}
if (accumulator >= from) {
results.push(...mapped)
assigned += count
}
accumulator += count
if (currentCityPage === currentCityMaxPage) {
currentCityIndex++
currentCityPage = 0
}
}
}
const sliced = results.slice(0, PAGE_SIZE)
return sliced
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment