betterator
TypeScript icon, indicating that this package has built-in type declarations

2.0.2 • Public • Published

betterator

A better sync and async iterator API.

Features

  • Intuitive: easy to use hasNext and getNext methods
  • Familiar: lots of other programming languages use the same API
  • Tiny: ~400 bytes minzipped
  • Awesome Name: you have to admit it's pretty rad 😎

Install

$ npm i betterator

Usage

import { Betterator, AsyncBetterator } from 'betterator'

const slothActivities = [`sleeping`, `eating`, `climbing`]

// Or `new Betterator(slothActivities[Symbol.iterator]())`
const iterator = Betterator.fromIterable(slothActivities)

while (iterator.hasNext()) {
  console.log(iterator.getNext())
}
//=> sleeping
//=> eating
//=> climbing

try {
  iterator.getNext()
} catch (e) {
  console.log(e.message)
}
//=> Doesn't have next

console.log(iterator.getNextOr(() => `being lazy`))
//=> being lazy

const asyncSlothActivities = (async function* () {
  yield* slothActivities
})()

// Or `new AsyncBetterator(slothActivities[Symbol.asyncIterator]())`
const asyncIterator = AsyncBetterator.fromAsyncIterable(asyncSlothActivities)

while (await asyncIterator.hasNext()) {
  console.log(await asyncIterator.getNext())
}
//=> sleeping
//=> eating
//=> climbing

try {
  await asyncIterator.getNext()
} catch (e) {
  console.log(e.message)
}
//=> Doesn't have next

const delay = timeout => new Promise(resolve => setTimeout(resolve, timeout))
console.log(
  await asyncIterator.getNextOr(() => delay(10).then(() => `being lazy`)),
)
//=> being lazy

See the type definitions for more documentation.

Contributing

Stars are always welcome!

For bugs and feature requests, please create an issue.

For pull requests, please read the contributing guidelines.

License

Apache 2.0

This is not an official Google product.

Package Sidebar

Install

npm i betterator

Weekly Downloads

68

Version

2.0.2

License

Apache-2.0

Unpacked Size

24.1 kB

Total Files

6

Last publish

Collaborators

  • tomeraberbach