iterators/doc/use.md

50 lines
1.5 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## Use
Examples (edge cases can be found in each function's documentation):
```typescript
// Create iterables
const i1 = iarray([1, 2, 3]); // 1 2 3
const i2 = isingle(4); // 4
const i3 = irecur(0, (x) => x - 1); // 0 -1 -2 -3 -4 ...
const i4 = irange(5); // 0 1 2 3 4
const i5 = irange(5, 1, 2); // 1 3 5 7 9
const i6 = istep(4, iarray([1, 10, 1, -1])); // 4 5 15 16 15
const i7 = irepeat(2); // 2 2 2 2 2 ...
// Consume iterables
iforeach(i1, console.log);
ifirst(i6); // 4
ifirstmap(i1, (x) => x > 1 ? -x : null); // -2
imaterialize(i1); // [1, 2, 3]
ilength(i1); // 3
iat(i5, 3); // 7
ireduce(i1, (a, b) => a + b, 0); // 6
isum(i1); // 6
icat(iarray(["a", "b", "c"])); // abc
imin(i1); // 1
imax(i1); // 3
// Transform iterables
iloop(i1); // 1 2 3 1 2 3 ...
iskip(i3, 2); // -2 -3 -4 -5 -6 ...
imap(i1, (x) => x * 2); // 2 4 6
ifilter(i3, (x) => x % 4 == 0); // 0 -4 -8 -12 ...
imapfilter(i1, (x) => x != 4 ? x * 2 : null); // 2 6
ipartition(i3, (x) => x % 4 == 0); // [0 -4 -8 ..., -1 -2 -3 -5 ...]
iunique(iarray([1, 4, 2, 4, 3, 1, 5])); // 1 4 2 3 5
// Combine iterables
ichain(i1, i2); // 1 2 3 4
ichainit(iarray([i1, i2])); // 1 2 3 4
icombine(iarray([0, 1]), iarray(["a", "b"])); // [0, "a"] [0, "b"] [1, "a"] [2, "b"]
izip(iarray([0, 1]), iarray(["a", "b"])); // [0, "a"] [1, "b"]
ialternate(iarray([0, 1]), iarray(["a", "b"])); // 0 "a" 1 "b"
// Type filter (result is a typed iterable)
ifiltertype(iarray([1, "a", 2, "b"]), (x): x is number => typeof x == "number"); // 1 2
class A {}
class B {}
ifilterclass(iarray([new A(), new B(), new A()]), A); // A A
```