Skip to content

Iterables Background

Iterables Background

@lou.codes/iterables is a collection of curried utils to work with iterables in a functional fashion without having to use for, while and so on directly.

Why

I always liked the curried approach of stuff like map in which you generate a mapping function first:

mapDouble.js
1
const mapDouble = map(value => value * 2);

And then you can use it to map any array:

index.js
1
import { mapDouble } from "./mapDouble.js";
2
3
mapDouble([1, 2, 3]); // [2, 4, 6]
4
// Instead of [1, 2, 3].map(value => value * 2); every time.

When I discovered how powerful that style was, I wanted to use it all over. Now the โ€œlimitationโ€ of those types of functions is that they first run the mapping function on every item, before going to the next. Iterators on the other side run all functions on each item, which in some scenarios can be more efficient.

1
// Regular mapping:
2
[1, 2, 3]
3
.map(plusOne)
4
.map(double)
5
.forEach(console.log);
6
/*
7
Runs like this:
8
- [2, 3, 4].
9
- [4, 6, 8].
10
- Logs 4, 6, 8.
11
*/
12
13
// Iterators:
14
[1, 2, 3]
15
|> map(plusOne)(%)
16
|> map(double)(%)
17
|> forEach(console.log)(%)
18
/*
19
Runs like this:
20
- 2 -> 4 -> Logs 4.
21
- 3 -> 6 -> Logs 6.
22
- 4 -> 8 -> Logs 8.
23
*/

This from my point of view is great, so I wanted to have a library that would allow me to use this style of programming with iterators, and thatโ€™s how this library was born.

How

I built this library using TypeScript, with configurations from my shared configs. I made it ESM only as soon as Node started supporting ESM modules, and I made it tree-shakeable by using named exports.

Over the development of this library I found some challenges like making the result of iterators iterable again, so we can map multiple times from the same iterator.

I went back and forward with the idea of making utils handle async automatically, but the cost in size and performance made me decide to split the utils into @lou.codes/iterables and @lou.codes/iterables/asynchronous.

Where

This library proved to be really useful for me, so I used it for others like cron, notify and window-open-promise.

Iโ€™ve also used it in some private projects, with great results.