Collections
Introduction
A Collection is a fluent wrapper around an array. It gives you a long chain of readable methods for transforming, filtering, grouping and summarising lists, and most of them return a new collection so you can keep chaining. It lives in @plinthjs/support, the package every other Plinth package builds on, and it is also what the framework hands you in many places, such as Schedule.collect().
LazyCollection is the sibling for large or unbounded sequences. It does the same kind of chaining but processes one item at a time, only as far as you need.
pnpm add @plinthjs/supportCreating collections
Wrap any iterable with collect(), or use the static constructors.
import { Collection, collect } from '@plinthjs/support'
collect([1, 2, 3]).all() // => [1, 2, 3]
new Collection(new Set([1, 2])).all() // => [1, 2]
Collection.make([1, 2]).all() // => [1, 2]
Collection.times(3, (n) => n * n).all() // => [1, 4, 9] (n starts at 1)
Collection.range(1, 4).all() // => [1, 2, 3, 4]
Collection.wrap('a').all() // => ['a'] (a single value becomes a one item list)all() and toArray() return a copy of the underlying array, count() returns the length, and a collection is iterable, so for...of and spread work on it.
const names = collect(['Ada', 'Linus'])
names.count() // => 2
names.isEmpty() // => false
for (const name of names) console.log(name)
JSON.stringify(names) // => '["Ada","Linus"]'The examples on this page use this list of users:
const users = collect([
{ id: 1, name: 'Ada', age: 36, role: 'admin' },
{ id: 2, name: 'Linus', age: 28, role: 'dev' },
{ id: 3, name: 'Grace', age: 45, role: 'admin' },
{ id: 4, name: 'Ken', age: null, role: 'dev' },
])Dot paths
Wherever a method takes a key, it can be a dot path such as 'address.city' that reaches into nested objects, or a function that computes the value.
Immutable by default
Almost every method returns a new collection and leaves the original untouched.
const items = collect([1, 2, 3])
const more = items.push(4)
items.all() // => [1, 2, 3]
more.all() // => [1, 2, 3, 4]The exceptions are the methods that exist to change a collection in place: transform, put, forget, pull, pop, shift and splice. They are listed under Changing a collection in place.
Transforming
map() returns a new collection of the callback results. flatMap() maps and then flattens one level.
collect([1, 2, 3])
.map((n) => n * 2)
.all() // => [2, 4, 6]
collect([1, 2])
.flatMap((n) => [n, n * 10])
.all() // => [1, 10, 2, 20]pluck() extracts one field from every item. Give it a second argument to key the result by another field, which returns a plain object instead of a collection.
users.pluck('name') // Collection of 'Ada', 'Linus', 'Grace', 'Ken'
users.pluck('name', 'id') // => { 1: 'Ada', 2: 'Linus', 3: 'Grace', 4: 'Ken' }mapWithKeys() builds an object from [key, value] pairs. mapInto() wraps each item in a class, and mapSpread() spreads each nested array into the callback's arguments.
users.mapWithKeys((u) => [u.name, u.age]) // => { Ada: 36, Linus: 28, Grace: 45, Ken: null }
collect([
[1, 2],
[3, 4],
])
.mapSpread((a, b) => a + b)
.all() // => [3, 7]
collect([1]).mapInto(Wrapper).all() // => [Wrapper { ... }]flatten(depth?) flattens nested arrays completely, or to the depth you give. collapse() merges a collection of arrays into one level.
collect([[1, [2]], [3]])
.flatten()
.all() // => [1, 2, 3]
collect([[1, [2]], [3]])
.flatten(1)
.all() // => [1, [2], 3]
collect([[1], [2, 3]])
.collapse()
.all() // => [1, 2, 3]dot() flattens a nested object into dot-path keys.
collect([{ a: { b: 1 } }]).dot() // => { 'a.b': 1 }Filtering
filter() keeps the items for which the callback is true, and with no callback it drops falsy values. reject() is the opposite.
collect([0, 1, 2, null, 3]).filter().all() // => [1, 2, 3]
collect([1, 2, 3, 4])
.reject((n) => n % 2 === 0)
.all() // => [1, 3]The where family filters objects by a field.
users.where('role', 'admin') // strict equality: Ada and Grace
users.where('age') // keeps items where age is truthy
users.whereIn('id', [1, 3]) // Ada and Grace
users.whereNotIn('role', ['dev']) // Ada and Grace
users.whereNull('age') // Ken
users.whereNotNull('age') // everyone but Ken
users.whereBetween('age', [30, 50]) // Ada and Grace
users.whereNotBetween('age', [30, 50]) // Linus and Kenwhere, whereIn and whereNotIn compare with strict equality already. whereStrict, whereInStrict and whereNotInStrict exist as explicit aliases. whereInstanceOf(Class) keeps items that are instances of a class.
unique() removes duplicates, by value or by a key, and duplicates() returns the repeated values.
collect([1, 1, 2]).unique().all() // => [1, 2]
users.unique('role').pluck('name') // Ada, Linus
collect([1, 2, 2, 3, 3]).duplicates().all() // => [2, 3]Taking and skipping
collect([1, 2, 3, 4]).take(2).all() // => [1, 2]
collect([1, 2, 3, 4]).take(-2).all() // => [3, 4] (negative counts from the end)
collect([1, 2, 3, 4]).skip(2).all() // => [3, 4]
collect([1, 2, 3, 4, 5]).slice(1, 3).all() // => [2, 3]
collect([1, 2, 3, 1])
.takeWhile((n) => n < 3)
.all() // => [1, 2]
collect([1, 2, 3, 1])
.takeUntil((n) => n >= 3)
.all() // => [1, 2]
collect([1, 2, 3, 1])
.skipWhile((n) => n < 3)
.all() // => [3, 1]
collect([1, 2, 3, 1])
.skipUntil((n) => n >= 3)
.all() // => [3, 1]
collect([1, 2, 3, 4, 5, 6]).nth(2).all() // => [1, 3, 5] (every second item)
collect([1, 2, 3, 4, 5, 6]).nth(2, 1).all() // => [2, 4, 6] (starting at offset 1)only(indexes) and except(indexes) keep or drop items by position, and forPage(page, perPage) returns one page of a list.
collect(['a', 'b', 'c']).only([0, 2]).all() // => ['a', 'c']
collect(['a', 'b', 'c']).except([0]).all() // => ['b', 'c']
collect([1, 2, 3, 4, 5]).forPage(2, 2).all() // => [3, 4]Retrieving single items
collect([1, 2, 3]).first() // => 1
collect([1, 2, 3]).first((n) => n > 1) // => 2
collect<number>([]).first(undefined, 'none') // => 'none' (the second argument is a default)
collect([1, 2, 3]).last() // => 3
collect([1, 2]).get(5, 'fallback') // => 'fallback'
users.firstWhere('role', 'dev') // Linus
users.value('name') // => 'Ada' (a field from the first item)sole() returns the only matching item and throws if there are none or more than one. firstOrFail() returns the first match and throws if there is none.
collect([1, 2, 3]).sole((n) => n === 2) // => 2
collect([1, 2]).sole() // throws: Collection.sole(): 2 items matched.
collect([]).firstOrFail() // throws: Collection.firstOrFail(): no matching items.Aggregating
collect([1, 2, 3]).sum() // => 6
users.sum('id') // => 10
collect([1, 2, 3, 4]).avg() // => 2.5
collect([3, 1]).min() // => 1
users.max('id') // => 4
collect([1, 3, 2, 4]).median() // => 2.5
collect([1, 2, 2, 3, 3]).mode() // => [2, 3]
collect([1, 2, 3, 4]).percentage((n) => n > 2) // => 50avg, min, max, median and mode return undefined for an empty collection. reduce() folds the collection into one value, and reduceSpread() carries several values through the fold.
collect([1, 2, 3]).reduce((carry, n) => carry + n, 0) // => 6
collect([1, 2, 3]).reduceSpread((sum, product, n) => [sum + n, product * n], 0, 1) // => [6, 6]Testing contents
collect([1, 2]).contains(2) // => true
collect([1, 2]).contains((n) => n > 5) // => false
collect([1, 2]).doesntContain(3) // => true
collect([1, 2]).every((n) => n > 0) // => true
collect([1, 2]).some((n) => n > 1) // => true
collect([1]).containsOneItem() // => true
collect(['a', 'b']).search('b') // => 1 (the index, or false when missing)Grouping and keyed operations
Methods that produce a keyed result return a plain object, not a collection.
groupBy() groups items under a key. keyBy() indexes them by a key and keeps the last item for each key. countBy() counts how many items share each key.
users.groupBy('role')
// => { admin: [Ada, Grace], dev: [Linus, Ken] }
collect([1, 2, 3, 4, 5]).groupBy((n) => (n % 2 ? 'odd' : 'even'))
// => { odd: [1, 3, 5], even: [2, 4] }
users.keyBy('id') // => { 1: Ada, 2: Linus, 3: Grace, 4: Ken }
collect(['a', 'b', 'a']).countBy() // => { a: 2, b: 1 }
collect([1, 2, 3, 4]).countBy((n) => (n % 2 ? 'odd' : 'even')) // => { odd: 2, even: 2 }mapToGroups() maps each item to a [key, value] pair and groups the values by key. combine() pairs this collection as keys with another list as values. flip() maps each value to its index.
collect([1, 2, 3]).mapToGroups((n) => [n % 2 ? 'odd' : 'even', n]) // => { odd: [1, 3], even: [2] }
collect(['a', 'b']).combine([1, 2]) // => { a: 1, b: 2 }
collect(['a', 'b']).flip() // => { a: 0, b: 1 }Because a grouped result is an object, wrap it again when you want to keep chaining: collect(Object.entries(users.groupBy('role'))).
Sorting
sortBy() sorts by a key or a computed value, ascending. sortByDesc() sorts descending. sort() takes a comparison function and defaults to ascending order, and sortDesc() reverses that.
users.sortBy('name').pluck('name') // Ada, Grace, Ken, Linus
users.sortByDesc('id').pluck('id') // 4, 3, 2, 1
users.sortBy((u) => -u.id).pluck('id') // 4, 3, 2, 1
collect([3, 1, 2]).sort().all() // => [1, 2, 3]
collect([3, 1, 2]).sortDesc().all() // => [3, 2, 1]
collect([1, 2, 3]).reverse().all() // => [3, 2, 1]sortKeys(), sortKeysDesc() and sortKeysUsing(compare) sort the keys of each object item.
collect([{ b: 1, a: 2 }])
.sortKeys()
.all() // => [{ a: 2, b: 1 }]shuffle() returns the items in random order and random() returns one random item. Both take an optional random-number function (returning a number from 0 up to 1) for tests; random(() => 0) returns the first item.
Merging, combining and splitting
collect([1]).merge([2, 3]).all() // => [1, 2, 3]
collect([1]).concat([2]).all() // => [1, 2]
collect([1, 2, 3]).diff([2]).all() // => [1, 3]
collect([1, 2, 3]).intersect([2, 3, 4]).all() // => [2, 3]
collect([1]).pad(3, 0).all() // => [1, 0, 0]
collect([1]).multiply(3).all() // => [1, 1, 1]push() and prepend() add items at the end and the start, returning a new collection.
Zip and cross join
zip() pairs items by position. crossJoin() produces every combination.
collect([1, 2]).zip(['a', 'b']).all() // => [[1, 'a'], [2, 'b']]
collect([1, 2]).crossJoin(['a', 'b']).all() // => [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]Partition
partition() splits a collection into two by a test: the items that pass first, the rest second.
const [evens, odds] = collect([1, 2, 3, 4]).partition((n) => n % 2 === 0)
evens.all() // => [2, 4]
odds.all() // => [1, 3]Chunking
collect([1, 2, 3, 4, 5]).chunk(2).all() // => [[1, 2], [3, 4], [5]]
collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).split(3) // groups of as-even-as-possible size: [1..4], [5..7], [8..10]
collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).splitIn(3) // fills each group first: [1..4], [5..8], [9, 10]
collect([1, 2, 3, 4]).sliding(2).all() // overlapping windows: [1, 2], [2, 3], [3, 4]
collect([1, 2, 3, 4, 5]).sliding(3, 2).all() // windows of 3 every 2 items: [1, 2, 3], [3, 4, 5]Replacing and uniting by position
A collection is a list, so replace(), union(), mergeRecursive() and replaceRecursive() work by index (list semantics), not by key or value. replace([9]) overwrites the item at index 0 and never grows the list, and union() is not a set union: it adds only the items of the other list at indexes beyond this collection's length. For value de-duplication, use merge() followed by unique().
collect([1, 2, 3]).replace([9]).all() // => [9, 2, 3]
collect([1, 2]).union([2, 3]).all() // => [1, 2]
collect([1, 2]).merge([2, 3]).unique().all() // => [1, 2, 3]Joining into strings
collect(['a', 'b', 'c']).join(', ') // => 'a, b, c'
collect(['a', 'b', 'c']).join(', ', ' and ') // => 'a, b and c'
users.implode('name', ' | ') // => 'Ada | Linus | Grace | Ken'Higher-order helpers
each() runs a callback for every item, and returning false from it stops the loop. It returns the collection.
collect([1, 2, 3]).each((n) => {
console.log(n)
if (n === 2) return false
})
// logs 1, 2tap() runs a callback with the whole collection and returns the collection unchanged, which is handy for debugging mid-chain. pipe() passes the collection to a callback and returns whatever the callback returns. pipeThrough() does that for a list of callbacks in order, and pipeInto() passes the collection to a class constructor.
collect([1, 2])
.tap((c) => console.log(c.count()))
.pipe((c) => c.sum()) // => 3whenEmpty() and whenNotEmpty() run a callback that returns a collection only when the collection is empty (or not), and otherwise leave it alone.
collect<number>([])
.whenEmpty((c) => c.push(1))
.all() // => [1]
collect([1])
.whenNotEmpty((c) => c.push(2))
.all() // => [1, 2]Changing a collection in place
These methods modify the collection they are called on.
collect([1, 2]).transform((n) => n * 2) // => the same collection, now [2, 4]
collect([1, 2]).put(0, 9) // set the item at index 0 to 9
collect([1, 2, 3]).forget(0) // remove the item at index 0
collect([1, 2, 3]).pop() // => 3 (removes and returns the last item)
collect([1, 2, 3]).shift() // => 1 (removes and returns the first item)
collect([1, 2, 3, 4]).splice(1, 2) // => a collection of the removed items [2, 3]pull(index) removes the item at an index and returns it:
const items = collect([1, 2, 3])
items.pull(1) // => 2
items.all() // => [1, 3]Lazy collections
A LazyCollection wraps a generator or any iterable and evaluates it on demand. Nothing runs until you ask for a result, and each item flows through the whole chain before the next one is read. That keeps memory flat for huge sequences, and it lets you work with sequences that never end.
import { LazyCollection } from '@plinthjs/support'
let seen = 0
const firstThree = LazyCollection.range(1, 1_000_000)
.map((n) => {
seen++
return n * 2
})
.filter((n) => n % 3 === 0)
.take(3)
.toArray()
firstThree // => [6, 12, 18]
seen // => 9 (only nine of the million items were ever visited)Create one from a generator function, from any iterable, or with make(), times() or range(). A generator function is called again every time the collection is consumed, so the same lazy collection can be used more than once.
function* numbers() {
yield 1
yield 2
yield 3
}
const lazy = LazyCollection.make(numbers)
lazy.map((n) => n + 1).toArray() // => [2, 3, 4]
lazy.sum() // => 6A lazy collection supports map, filter, reject, take, skip, takeWhile and takeUntil as lazy steps. These ones consume it: each, first, reduce, sum, count, toArray and collect.
LazyCollection.range(1, 10).skip(2).take(3).toArray() // => [3, 4, 5]
LazyCollection.range(1, 10)
.takeWhile((n) => n < 4)
.toArray() // => [1, 2, 3]
LazyCollection.range(1, 5)
.reject((n) => n % 2 === 0)
.toArray() // => [1, 3, 5]
LazyCollection.range(1, 3).sum((n) => n * 2) // => 12first() stops reading as soon as it finds a match, so it works on an infinite generator.
function* naturals() {
let n = 0
while (true) yield n++
}
LazyCollection.make(naturals).first((n) => n > 5) // => 6Convert in either direction with collect() on a lazy collection, which reads everything into a Collection, and lazy() on a Collection:
LazyCollection.make(numbers).collect().all() // => [1, 2, 3]
collect([1, 2])
.lazy()
.map((n) => n + 1)
.toArray() // => [2, 3]Use a lazy collection when the input is large, comes from a stream, or is infinite, and a plain Collection for everything else. Only the methods listed above exist on LazyCollection. To use any other method, call collect() first.
Extending collections
Collection does not have a built-in macro registry. Add your own methods by subclassing it.
import { Collection } from '@plinthjs/support'
class UserCollection extends Collection<{ name: string; age: number | null }> {
adults(): UserCollection {
return new UserCollection(this.filter((u) => (u.age ?? 0) >= 18))
}
}
new UserCollection([{ name: 'Ada', age: 36 }]).adults().count() // => 1For classes of your own that should accept methods registered at runtime, the Macroable mixin provides macro(), mixin() and hasMacro(). See Helpers.
Related
Query results and many other lists in the framework are plain arrays you can pass to collect(). For string, array and number helpers that work alongside collections, see Helpers.