Skip to main content

Collection usage

The collection module provides a fluent, convenient wrapper for working with Arrays, Iterables and AsyncIterables.

Creating a collection

You can create a collection from an any object thats implements the Iterable contract.

Create a collection from an Array:

import { ICollection, ListCollection } from "@daiso-tech/core/collection";

const fromArray = new ListCollection([1, 2, 3, 4]);

// Logs [1, 2, 3, 4]
console.log(fromArray.toArray());

Create a collection from an string:

const fromString = new ListCollection("abc");
// Logs ["a", "b", "c"]
console.log(fromString.toArray());

Create a collection from a Set:

const fromSet = new ListCollection(new Set([1, 2, 2 4]));
// Logs [1, 2, 4]
console.log(fromSet.toArray());

Create a collection from a Map:

const fromMap = new ListCollection(
new Map([
["a", 1],
["b", 2],
]),
);
// Logs [["a", 1], ["b", 2]]
console.log(fromMap.toArray());

Create collection from your own object that implements Iterable contract:

class MyIterable implements Iterable<number> {
*[Symbol.iterator](): Iterator<number> {
yield 1;
yield 2;
yield 3;
}
}

const fromIterable: ListCollection<number> = new ListCollection(
new MyIterable(),
);
// Logs [1, 2, 3]
console.log(fromIterable.toArray());

Immutability

The collection is imutable, meaning that all methods will return a new collection and not modify the original collection.

import { ListCollection } from "@daiso-tech/core/collection";

const original = new ListCollection([1, 2, 3]);
const modified = original.map((item) => item * 2);

// Logs [1, 2, 3]
console.log(original.toArray());

// Logs [2, 4, 6]
console.log(modified.toArray());

Acessing elements from a collection

To access elements from a collection you can use the get method. The get method will return the item at the specified index. If the index is out of bounds, it will return null.

import { ListCollection } from "@daiso-tech/core/collection";

const collection = new ListCollection([1, 2, 3]);

const value = collection.get(1);

// Logs 2
console.log(value);

If you want to get the item at the specified index but return a default value if the index is out of bounds, you can use the getOr method.

import { ListCollection } from "@daiso-tech/core/collection";
const collection = new ListCollection([1, 2, 3]);
const value = collection.getOr(1, -1);
// Logs 2
console.log(value);

const value2 = collection.getOr(5, -1);
// Logs -1
console.log(value2);

If you want to get the item at the specified index and throw an error if the index is out of bounds, you can use the getOrFail method.

import { ListCollection } from "@daiso-tech/core/collection";
const collection = new ListCollection([1, 2, 3]);
const value = collection.getOrFail(1);
// Logs 2
console.log(value);

// throws error
const value2 = collection.getOrFail(5);
info

All methods that ends with Or will return the item if it exists or a default value.

All methods that ends with OrFail it will return the item if it exists or throw an error.

Iterating over a collection

Since it is Iterable you can also use the for of loop to iterate over a collection.

import { ListCollection } from "@daiso-tech/core/collection";

const collection = new ListCollection([1, 2, 3]);

// Logs 1, 2, 3
for (const item of collection) {
console.log(item);
}

Modifying and filtering a collection

You can modify the collection by using for example the map method:

import { ListCollection } from "@daiso-tech/core/collection";

const collection = new ListCollection([1, 2, 3]).map((value) => value * value);

// Logs [1, 4, 9]
console.log(collection.toArray());

You can filter the collection by using for example the filter method:

import { ListCollection } from "@daiso-tech/core/collection";

const collection = new ListCollection([1, 2, 3, 4, 5, 6]).filter(
(value) => value % 2 === 0,
);

// Logs [2, 4, 5]
console.log(collection.toArray());
info

All methods that iterate, modify, or filter the collection expect a callback function with three arguments in the following order

  1. item: The current element being processed.

  2. index: The index of the current element.

  3. collection: The original collection being traversed.

import { ListCollection } from "@daiso-tech/core/collection";

const collection = new ListCollection([2, 3, 2, 3, 4, 3]).filter(
(item, index, collection) => {
// Logs each item
console.log("item:", item);

// Logs each index of the item
console.log("index:", index);

// Logs the original collection
console.log("collection:", collection.toArray());
return item === 2;
},
);

collection.toArray();

Types of collections

The library includes 3 types of collections:

Serialization and deserialization

The ListCollection and IterableCollection classes supports serialization and deserialization, allowing you to easily convert instances to and from serialized formats. However, registration is required first:

import { Serde } from "@daiso-tech/core/serde";
import { SuperJsonSerdeAdapter } from "@daiso-tech/core/serde/adapters";
import { TimeSpan } from "@daiso-tech/core/utilities";
import {
ListCollection,
IteralbeCollection,
} from "@daiso-tech/core/collection";

const serde = new Serde(new SuperJsonSerdeAdapter());

serde.registerClass(ListCollection);
serde.registerClass(IteralbeCollection);

const listCollection = new ListCollection([1, 2, 3, 4, 5]);
const serializedListCollection = serde.serialize(timeSpan);
const deserializedListCollection = serde.deserialize(serializedTimeSpan);

// Logs false
console.log(serializedListCollection === deserializedListCollection);
// Logs [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
console.log(listCollection.toArray(), deserializedListCollection.toArray());

const iterableCollection = new IteralbeCollection([1, 2, 3, 4, 5]);
const serializedIteralbeCollection = serde.serialize(timeSpan);
const deserializedIteralbeCollection = serde.deserialize(serializedTimeSpan);

// Logs false
console.log(serializedIteralbeCollection === deserializedIteralbeCollection);
// Logs [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
console.log(
iterableCollection.toArray(),
deserializedIteralbeCollection.toArray(),
);

Available Methods

For the remaining of the documentation, we'll discuss each method available on the ICollection contract.

Instance methods

Static methods

Instance methods

after

The after method returns the item that comes after the first item that matches predicateFn. If the collection is empty or the predicateFn does not match or matches the last item then null is returned.

import { ListCollection } from "@daiso-tech/core/collection";
new ListCollection([1, 2, 3, 4]).after((item) => item === 2);
// 3

afterOr

The afterOr method returns the item that comes after the first item that matches predicateFn. If the collection is empty or the predicateFn does not match or matches the last item then defaultValue is returned.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4]).afterOr(-1, (item) => item === 4);
// -1

afterOrFail

The afterOrFail method returns the item that comes after the first item that matches predicateFn. If the collection is empty or the predicateFn does not match or matches the last item then an error is thrown.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4]).afterOrFail((item) => item === 4);
// throws error

append

The append method adds Iterable to the end of the collection.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4, 5]).append([-1, -2]).toArray();
// [1, 2, 3, 4, 5, -1, -2]

average

The average method returns the average of all items in the collection. If the collection includes other than number items an error will be thrown. If the collection is empty an error will also be thrown.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3]).average();
// 2

before

The before method returns the item that comes before the first item that matches predicateFn. If the predicateFn does not match or matches the first item then null is returned.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4]).before((item) => item === 2);
// 1

beforeOr

The beforeOr method returns the item that comes before the first item that matches predicateFn. If the collection is empty or the predicateFn does not match or matches the first item then defaultValue is returned.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4]).beforeOr(-1, (item) => item === 2);
// 1

beforeOrFail

The beforeOrFail method returns the item that comes before the first item that matches predicateFn. If the collection is empty or the predicateFn does not match or matches the first item then an error is thrown.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4]).beforeOrFail((item) => item === 1);
// throws error

change

The change method changes only the items that passes predicateFn using mapFn.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4, 5])
.change(item => item % 2 === 0, item => item \* 2)
.toArray();
// [1, 4, 3, 8, 5]

chunk

The chunk method breaks the collection into multiple, smaller collections of size chunkSize. If chunkSize is not divisible with total number of items then the last chunk will contain the remaining items.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4, 5, 6, 7])
.chunk(4)
.map((chunk) => chunk.toArray())
.toArray();
// [[1, 2, 3, 4], [5, 6, 7]]

chunkWhile

The chunkWhile method breaks the collection into multiple, smaller collections based on the evaluation of predicateFn. The chunk variable passed to the predicateFn may be used to inspect the previous item.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection("AABBCCCD")
.chunkWhile((item, _index, chunk) => item === chunk.last())
.map((chunk) => chunk.toArray())
.toArray();
// [["A", "A"], ["B", "B"], ["C", "C", "C"], ["D"]]

collapse

The collapse method collapses a collection of iterables into a single, flat collection.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([
[1, 2],
[3, 4],
])
.collapse()
.toArray();
// [1, 2, 3, 4]

count

The count method returns the total number of items in the collection that passes predicateFn.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4, 5, 6]).count((value) => value % 2 === 0);
// 3

countBy

The countBy method counts the occurrences of values in the collection by selectFn. By default the equality check occurs on the item.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection(["a", "a", "a", "b", "b", "c"]).countBy().toArray();
// [["a", 3], ["b", 2], ["c", 1]]

crossJoin

The crossJoin method cross joins the collection's values among iterables, returning a Cartesian product with all possible permutations.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2]).crossJoin(["a", "b"]).toArray();
// [[1, "a"], [1, "b"], [2, "a"], [2, "b"]]

entries

The entries returns an ListCollection of key, value pairs for every entry in the collection.

import { ListCollection } from "@daiso-tech/core/collection";

const collection = new ListCollection(["a", "b", "c", "d"]).entries().toArray();
// [[0, "a"], [1, "b"], [2, "c"], [3, "d"]]

every

The every method determines whether all items in the collection matches predicateFn.

import { ListCollection } from "@daiso-tech/core/collection";

const isAllNumberLessThan6 = new ListCollection([0, 1, 2, 3, 4, 5]).every(
(item) => item < 6,
);
// true

filter

The filter method filters the collection using predicateFn, keeping only those items that pass predicateFn.

import { ListCollection } from "@daiso-tech/core/collection/collection";

new ListCollection([0, 1, 2, 3, 4, 5, 6])
.filter((item) => 2 < item && item < 5)
.toArray();
// [3, 4]

validate

The validate method filters all items that matches the schema and transforms them afterwards. The schema can be any standard schema.

import { ListCollection } from "@daiso-tech/core/collection/collection";
import { z } from "zod";

new ListCollection(["a", "1.2", "3", "null"])
.validate(z.string().pipe(z.number()))
.toArray();
// [1.2, 3]

first

The first method returns the first item in the collection that passes predicateFn. By default it will get the first item. If the collection is empty or no items passes predicateFn than null i returned.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4]).first();
// 1

firstOr

The firstOr method returns the first item in the collection that passes predicateFn By default it will get the first item. If the collection is empty or no items passes predicateFn than defaultValue.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4]).firstOr(-1, (item) => item > 10);
// -1

firstOrFail

The firstOrFail method returns the first item in the collection that passes predicateFn. By default it will get the first item. If the collection is empty or no items passes predicateFn than error is thrown.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4]).firstOrFail((item) => item === 5);
// throws error

flatMap

The flatMap method returns a new array formed by applying mapFn to each item of the array, and then collapses the result by one level. It is identical to a map method followed by a collapse method.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([
["a", "b"],
["c", "d"],
])
.flatMap((item) => [item.length, ...item])
.toArray();
// [2, "a", "b", 2, "c", "d"]

forEach

The forEach method iterates through all items in the collection.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3]).forEach((item) => console.log(item));
// Logs: 1, 2, 3

get

The get method returns the item by index. If the item is not found null will be returned.

import { ListCollection } from "@daiso-tech/core/collection";

const collection = new ListCollection([1, 4, 2, 8, -2]);
collection.get(2); // 2
collection.get(5); // null

getOrFail

The getOrFail method returns the item by index. If the item is not found an error will be thrown.

import { ListCollection } from "@daiso-tech/core/collection";

const collection = new ListCollection([1, 4, 2, 8, -2]);
collection.getOrFail(2); // 2
collection.getOrFail(5); // throws error

groupBy

The groupBy method groups the collection's items by selectFn. By default the equality check occurs on the item.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection(["a", "a", "a", "b", "b", "c"])
.groupBy()
.map(([k, v]) => [k, v.toArray()])
.toArray();
// [["a", ["a", "a", "a"]], ["b", ["b", "b"]], ["c", ["c"]]]

insertAfter

The insertAfter method adds Iterable after the first item that matches predicateFn.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 2, 3, 4, 5])
.insertAfter((item) => item === 2, [-1, 20])
.toArray();
// [1, 2, -1, 20, 2, 3, 4, 5]

insertBefore

The insertBefore method adds Iterable before the first item that matches predicateFn.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 2, 3, 4, 5])
.insertAfter((item) => item === 2, [-1, 20])
.toArray();
// [1, 2, -1, 20, 2, 3, 4, 5]

isEmpty

The isEmpty returns true if the collection is empty.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([]).isEmpty();
// true

isNotEmpty

The isEmpty returns true if the collection is empty.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([]).isEmpty();
// true

join

The join method joins the collection's items with separator. An error will be thrown when if a none string item is encounterd.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4]).map((item) => item.toString()).join();
// "1,2,3,4"
import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4]).map((item) => item.toString()).join("_");
// "1_2_3_4"

keys

The keys method returns an ListCollection of keys in the collection.

last

The last method returns the last item in the collection that passes predicateFn. By default it will get the last item. If the collection is empty or no items passes predicateFn than null i returned.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4]).last();
// 4

lastOr

The lastOr method returns the last item in the collection that passes predicateFn. By default it will get the last item. If the collection is empty or no items passes predicateFn than defaultValue.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4]).lastOr(-1, (item) => item > 10);
// -1

lastOrFail

The lastOrFail method returns the last item in the collection that passes predicateFn. By default it will get the last item. If the collection is empty or no items passes predicateFn than error is thrown.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4]).lastOrFail((item) => item === 5);
// throws error

map

The map method iterates through the collection and passes each item to mapFn. The mapFn is free to modify the item and return it, thus forming a new collection of modified items.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4, 5]).map((item) => item * 2).toArray();
// [2, 4, 6, 8, 10]

max

The max method returns the max of all items in the collection. If the collection includes other than number items an error will be thrown. If the collection is empty an error will also be thrown.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3]).max();
// 3

median

The median method returns the median of all items in the collection. If the collection includes other than number items an error will be thrown. If the collection is empty an error will also be thrown.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3]).median();
// 2

min

The min method returns the min of all items in the collection. If the collection includes other than number items an error will be thrown. If the collection is empty an error will also be thrown.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3]).min();
// 1

nth

The nth method creates a new collection consisting of every n-th item.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection(["a", "b", "c", "d", "e", "f"]).nth(4).toArray();
// ["a", "e"]

padEnd

The padEnd method pads this collection with fillItems until the resulting collection size reaches maxLength. The padding is applied from the end of this collection.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection("abc").padEnd(10, "foo").join("");
// "abcfoofoof"

padStart

The padStart method pads this collection with fillItems until the resulting collection size reaches maxLength. The padding is applied from the start of this collection.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection("abc").padStart(10, "foo").join("");
// "foofoofabc"

page

The page method returns a new collection containing the items that would be present on page with custom pageSize.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4, 5, 6, 7, 8, 9])
.page(
2, // Page number
3, // Page size
)
.toArray();
// [4, 5, 6]

partition

The partition method is used to separate items that pass predicateFn from those that do not.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4, 5, 6])
.partition((nbr) => nbr % 2 === 0)
.map((chunk) => chunk.toArray())
.toArray();
// [[2, 4, 6], [1, 3, 5]]

percentage

The percentage method may be used to quickly determine the percentage of items in the collection that pass predicateFn. If the collection is empty an error will also be thrown.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 1, 2, 2, 2, 3]).percentage((value) => value === 1);
// 33.333

pipe

The pipe method passes the orignal collection to callback and returns the result from callback.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, "2", "a", 1, 3, {}])
.pipe((c) => c.map((item) => Number(item)).reject(isNaN))
.pipe((c) => c.repeat(2).toArray());
// [1, 2, 1, 3]

prepend

The prepend method adds Iterable to the beginning of the collection.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4, 5]).prepend([-1, 20]).toArray();
// [-1, 20, 1, 2, 3, 4, 5]

reduce

The reduce method executes reduceFn function on each item of the array, passing in the return value from the calculation on the preceding item. The final result of running the reducer across all items of the array is a single value.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3]).reduce((sum, item) => sum + item);
// 6

reject

The reject method filters the collection using predicateFn, keeping only those items that not pass predicateFn.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4, 5, 6])
.reject((item) => 2 < item && item < 5)
.toArray();
// [1, 2, 5, 6]

repeat

The repeat method will repeat the original collection amount times.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3]).repeat(3).toArray();
// [1, 2, 3, 1, 2, 3, 1, 2, 3]

reverse

The reverse method will reverse the order of the collection. The reversing of the collection will be applied in chunks that are the size of chunkSize.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([-1, 2, 4, 3]).reverse().toArray();
// [3, 4, 2, -1]

searchFirst

The searchFirst return the index of the first item that matches predicateFn.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection(["a", "b", "b", "c"]).searchFirst((item) => item === "b");
// 1

searchLast

The searchLast return the index of the last item that matches predicateFn.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection(["a", "b", "b", "c"]).searchLast((item) => item === "b");
// 2

set

The set method updates the specified index with new value.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4, 5]).set(1, -1).toArray();
// [1, -1, 3, 4, 5]

shuffle

The shuffle method randomly shuffles the items in the collection. You can provide a custom Math.random function by passing in mathRandom.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4]).shuffle().toArray();
// Random order, e.g., [3, 1, 4, 2]

size

The size returns the size of the collection.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3]).size();
// 3

skip

The skip method skips the first offset items.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).skip(4).toArray();
// [5, 6, 7, 8, 9, 10]

skipUntil

The skipUntil method skips items until predicateFn returns true.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4]).skipUntil((item) => item >= 3).toArray();
// [3, 4]

skipWhile

The skipWhile method skips items until predicateFn returns false.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4]).skipWhile((item) => item <= 3).toArray();
// [4]

slice

The slice method creates porition of the original collection selected from start and end where start and end (end not included) represent the index of items in the collection.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection(["a", "b", "c", "d", "e", "f"]).slice(3).toArray();
// ["d", "e", "f"]

sliding

The sliding method returns a new collection of chunks representing a "sliding window" view of the items in the collection.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4, 5])
.sliding(2)
.map((chunk) => chunk.toArray())
.toArray();
// [[1, 2], [2, 3], [3, 4], [4, 5]]

sole

The sole method returns the first item in the collection that passes predicateFn, but only if predicateFn matches exactly one item. If no items matches or multiple items are found an error will be thrown.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4, 5]).sole((item) => item === 4);
// 4

some

The some method determines whether at least one item in the collection matches predicateFn.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([0, 1, 2, 3, 4, 5]).some((item) => item === 1);
// true

sort

The sort method sorts the collection. You can provide a comparator function.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([-1, 2, 4, 3]).sort().toArray();
// [-1, 2, 3, 4]

split

The split method breaks a collection evenly into chunkAmount of chunks.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4, 5])
.split(3)
.map((chunk) => chunk.toArray())
.toArray();
// [[1, 2], [3, 4], [5]]

sum

The sum method returns the sum of all items in the collection. If the collection includes other than number items an error will be thrown. If the collection is empty an error will also be thrown.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3]).sum();
// 6

take

The take method takes the first limit items.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([0, 1, 2, 3, 4, 5]).take(3).toArray();
// [0, 1, 2]
import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([0, 1, 2, 3, 4, 5]).take(-2).toArray();
// [0, 1, 2, 3]

takeUntil

The takeUntil method takes items until predicateFn returns true.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4]).takeUntil((item) => item >= 3).toArray();
// [1, 2]

takeWhile

The takeWhile method takes items until predicateFn returns false.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4]).takeWhile((item) => item < 4).toArray();
// [1, 2, 3]

tap

The tap method passes a copy of the original collection to callback, allowing you to do something with the items while not affecting the original collection.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4, 5, 6])
.tap((c) => c.filter((v) => v % 2 === 0).forEach(console.log))
.toArray();
// [1, 2, 3, 4, 5, 6] (logs 2, 4, 6)

toArray

The toArray method converts the collection to a new Array.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3]).toArray();
// [1, 2, 3]

toIterator

The toIterator method converts the collection to a Iterator.

const iterator = new ListCollection([1, 2, 3, 4, 5]).toIterator();

console.log("item 1:", iterator.next());
console.log("item 2:", iterator.next());
console.log("item 3:", iterator.next());
console.log("done:", iterator.next());

toMap

The toMap method converts the collection to a new Map. An error will be thrown if item is not a tuple of size 2.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([
[0, "a"],
[1, "b"],
]).toMap();
// Map { 0 => "a", 1 => "b" }

toRecord

The toRecord method converts the collection to a new Record. An error will be thrown if item is not a tuple of size 2 where the first element is a string or a number.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([
[0, "a"],
[1, "b"],
]).toRecord();
// { 0: "a", 1: "b" }

unique

The unique method removes all duplicate values from the collection by selectFn. By default the equality check occurs on the item.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 1, 2, 2, 3, 4, 2]).unique().toArray();
// [1, 2, 3, 4]

Equality check on a field in the item.

import { ListCollection } from "@daiso-tech/core/collection";

type Phone = { name: string; brand: string; type: string };

new ListCollection([
{ name: "iPhone 6", brand: "Apple", type: "phone" },
{ name: "iPhone 5", brand: "Apple", type: "phone" },
{ name: "Apple Watch", brand: "Apple", type: "watch" },
{ name: "Galaxy S6", brand: "Samsung", type: "phone" },
{ name: "Galaxy Gear", brand: "Samsung", type: "watch" },
])
.unique((item) => item.brand)
.toArray();
// [
// { name: "iPhone 6", brand: "Apple", type: "phone" },
// { name: "Galaxy S6", brand: "Samsung", type: "phone" },
// ]

copy

The copy method returns a copy of the collection.

import { ListCollection } from "@daiso-tech/core/collection";

const collectionA = new ListCollection([1, 2, 3, 4]);
const collectionB = collectionA.copy();

// Logs false
console.log(collectionA === collectionB);

// Logs false
console.log(collectionA.toArray() === collectionB.toArray());

when

The when method will execute callback when condition evaluates to true.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4])
.when(true, (c) => c.append([-3]))
.when(false, (c) => c.append([20]))
.toArray();
// [1, 2, 3, 4, -3]

whenEmpty

The whenEmpty method will execute callback when the collection is empty.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([]).whenEmpty((c) => c.append([-3])).toArray();
// [-3]
import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1]).whenEmpty((c) => c.append([-3])).toArray();
// [1]

whenNot

The whenNot method will execute callback when condition evaluates to false.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1, 2, 3, 4])
.whenNot(true, (c) => c.append([-3]))
.whenNot(false, (c) => c.append([20]))
.toArray();
// [1, 2, 3, 4, 20]

whenNotEmpty

The whenNotEmpty method will execute callback when the collection is not empty.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([]).whenNotEmpty((c) => c.append([-3])).toArray();
// []
import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([1]).whenNotEmpty((c) => c.append([-3])).toArray();
// [1, -3]

Static methods

concat

The concat method concatenates multiple Iterable's and returns a new collection.

import { ListCollection } from "@daiso-tech/core/collection";
ListCollection.concat([1, 2, 3], [4, 5, 6]).toArray();
// [1, 2, 3, 4, 5, 6]

difference

The difference method will return the values in the original collection that are not present in Iterable. By default the equality check occurs on the item.

new ListCollection([1, 2, 2, 3, 4, 5]).difference([2, 4, 6, 8]).toArray();
// [1, 3, 5]

Equality check on a field in the item.

import { ListCollection } from "@daiso-tech/core/collection";

new ListCollection([
{ name: "iPhone 6", brand: "Apple", type: "phone" },
{ name: "iPhone 5", brand: "Apple", type: "phone" },
{ name: "Apple Watch", brand: "Apple", type: "watch" },
{ name: "Galaxy S6", brand: "Samsung", type: "phone" },
{ name: "Galaxy Gear", brand: "Samsung", type: "watch" },
])
.difference(
[{ name: "Apple Watch", brand: "Apple", type: "watch" }],
// equality check occurs on product.type
(product) => product.type,
)
.toArray();
// [
// { name: "iPhone 6", brand: "Apple", type: "phone" },
// { name: "iPhone 5", brand: "Apple", type: "phone" },
// { name: "Galaxy S6", brand: "Samsung", type: "phone" },
// ]

The difference method is also available as a static method.

ListCollection.difference([1, 2, 2, 3, 4, 5], [2, 4, 6, 8]).toArray();
// [1, 3, 5]

zip

The zip method merges together the values of Iterable with the values of the collection at their corresponding index. The returned collection has size of the shortest collection. The zip method is also available as a static method.

import { ListCollection } from "@daiso-tech/core/collection";

ListCollection.zip(["Chair", "Desk"], [100, 200]).toArray();
// [["Chair", 100], ["Desk", 200]]