Skip to main content

Recipes

How do I associate values by a key?

import { map, pipe, reduce, toMap } from 'lfi'

console.log(
pipe(
[`sloth`, `dog`],
// Create an iterable of key-value pairs
map(animal => [animal.length, animal]),
// Collect the key-value pairs into a map
reduce(toMap()),
),
)
//=> Map(2) {
//=> 5 => 'sloth',
//=> 3 => 'dog'
//=> }
Playground

You can swap out toMap for another reducer to collect the key-value pairs into a different data structure. See the "Reducer" page for more details.

warning

If there are multiple key-value pairs with the same key, then only the last key-value pair is preserved.

How do I group values by a key?

import { map, pipe, reduce, toArray, toGrouped, toMap } from 'lfi'

console.log(
pipe(
[`sloth`, `cat`, `dog`, `bunny`],
// Create an iterable of key-value pairs
map(animal => [animal.length, animal]),
// Collect the values by key into a map where each group is an array
reduce(toGrouped(toArray(), toMap())),
),
)
//=> Map(2) {
//=> 5 => [ 'sloth', 'bunny' ],
//=> 3 => [ 'cat', 'dog' ]
//=> }
Playground

You can swap out both toArray and toMap for other reducers to collect the key-value pairs into different data structures. See the "Reducer" page for more details.

How do I limit the concurrency of a concur iterable?

You can wrap the async callback you want to limit the concurrency of with limit-concur.

import { asConcur, mapConcur, pipe, reduceConcur, toArray } from 'lfi'
import limitConcur from 'limit-concur'

let pendingRequests = 0
console.log(
await pipe(
asConcur([`strawberry`, `max`, `bitsy`, `tommy`]),
mapConcur(
// At most 2 requests at a time
limitConcur(2, async sloth => {
console.log(++pendingRequests)
const [adjective] = await (
await fetch(`https://random-word-form.herokuapp.com/random/adjective`)
).json()
console.log(--pendingRequests)
return `${adjective} ${sloth}`
}),
),
reduceConcur(toArray()),
),
)
//=> 1
//=> 2
//=> 1
//=> 2
//=> 1
//=> 2
//=> 1
//=> 0
//=> [ 'kind strawberry', 'humble max', 'great bitsy', 'beautiful tommy' ]
Playground