1.0.5 • Published 1 year ago

any-iter-utils v1.0.5

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

Utils for any iterable objects

build unit tests

Helpers for working with any iterable objects and some useful container types

Highly inspired by python itertools, rust std::iter and tc39 iterator-helpers

Getting started

Before start using the library use can additionally include prelude file which currenly contains only global types:

import 'any-iter-utils/prelude';

These types are used by the library and can be helpful if you decide to write your own helpers or something

See prelude.d.ts

If you want to use imports as it's shown below you should have typescript version >= 4.7 and moduleResolution setting in tsconfig.json:

{
  "compilerOptions": {
    "moduleResolution": "node16" // node16 | nodenext
  }
}

Otherwise you will have to import everything just from any-iter-utils not being able to specify the path. It will look like this:

import { map, SyncIter } from 'any-iter-utils';

Instead of this:

import { map } from 'any-iter-utils/combinators';
import { SyncIter } from 'any-iter-utils/containers';

It's because the library uses exports field in package.json which is not supported with other settings of typescript

Combinators

The basic usage of any helper would look like this:

import { map } from 'any-iter-utils/combinators';

const
  iterable = [1, 2, 3],
  mapper = (v: number) => v * 2;

map(iterable, mapper); // IterableIterator<2, 4, 6>

const asyncIterable = (async function* () {
  yield 1; yield 2; yield 3;
})();

map(asyncIterable, mapper); // AsyncIterableIterator<2, 4, 6>

See combinators for all available helpers

Collectors

If you want to collect your iterable into some data structure you can use collectors:

import { intoArr, intoSet } from 'any-iter-utils/collectors';

function* gen(): Generator<number> {
  yield 1; yield 2; yield 1;
}

intoArr(gen()); // [1, 2, 1]

async function* agen(): AsyncGenerator<number> {
  yield 1; yield 2; yield 1
}

intoSet(agen()); // Promise<Set<1, 2>>

Or a universal function collect. The example above is equivalent to:

import { collect } from 'any-iter-utils/collectors';

collect(gen(), []); // [1, 2, 1]
collect(agen(), new Set()); // Promise<Set<1, 2>>

Containers

Using only combinators sometimes can be more accurate but often it leads to something like this:

map(filter(map(filter(iterable, f1), f2), f3), f4);

To get rid of this problem you can use SyncIter and AsyncIter containers. The example above is equivalent to:

import { SyncIter } from 'any-iter-utils/containers';

SyncIter.from(iterable)
  .filter(f1)
  .map(f2)
  .filter(f3)
  .map(f4)

See containers for all available container types

Building

Install dependencies with npm ci, then run npm run build

The build command will generate esm bundle lib/esm, cjs bundle lib/cjs and declaration files in types folder