DEV Community

loading...

Discussion on: Is there a good temporary variable name that you use?

Collapse
qm3ster profile image
Mihail Malo

I would avoid naming them, by doing the following:

function getAllFooBar() {
  // find smart_collections
  const foos = apiCall('foo').items
  const bars = []
  // for every foo value
  for (const foo of foos) {
    let token = undefined
    do {
      // undefined skips key in JSON stringification
      const barResponse = apiCall('bar', {...foo, token})
      bars.push(...barResponse.items)
      token = barResponse.nextPageToken
    } while (token)
  }
}
Enter fullscreen mode Exit fullscreen mode

Usually I would abstract such a behavior that can probably be used for multiple paths of the API into a business-logic-indifferent function:

async function* getPaged(path: string, data?: any, token?: string) {
  do {
    const res = apiCall(path, {...data, token}).await
    for (const item of res.items) yield item
    token = res.nextPageToken
  } while (token)
}

async function getAllFooBar() {
  const all = []
  for (const foo of (await apiCall('foo')).items)
    for await (const x of getPaged('bar', foo))
      all.push(x)
  return all
}
Enter fullscreen mode Exit fullscreen mode
Collapse
klvenky profile image
venkatesh k Author

Thanks Mihail. This looks good.
I stopped using do-while for quite some time. This looks to a very good use case. Thanks :)

Collapse
qm3ster profile image
Mihail Malo

I wish it let me do while (token = res.newToken), but res goes out of scope there. Too bad for JS spec.

Thread Thread
klvenky profile image
venkatesh k Author

Yeah that wouldn't work in that case.