Sequence
Implements:
- Iterable
An iterable sequence that can be queried using ESLinq operators (like 'select', 'where', etc.).
Static Method Summary
Static Public Methods | ||
public static |
Returns an empty `Sequence`.
|
|
public static |
Returns an increasing sequence of integers, of `count` items,
starting at `start`.
|
|
public static |
Returns a `Sequence` that contains the specified element repeated
the specified number of times.
|
Constructor Summary
Public Constructor | ||
public |
constructor(The: Iterable) Creates a new `Sequence` instance wrapping the `iterable` specified.
|
Member Summary
Public Members | ||
public |
iterable: * |
Method Summary
Public Methods | ||
public |
aggregate(processNext: function(accumulator: *, current: *): *, seed: *, transformResult: function(result: *): *): * Applies an aggregation function over the sequence.
|
|
public |
Determines whether all elements satisfy a condition.
|
|
public |
Determines whether at least one element satisfies a condition.
|
|
public |
Calculates the average (arithmetic mean) of the elements of the sequence.
|
|
public |
Concatenates the iterable specified with the current one.
|
|
public |
Determines whether at least one element is equal to the item specified
using the strict equality operator.
|
|
public |
Returns the number of elements in the `Sequence`.
|
|
public |
defaultIfEmpty(defaultValue: *): Sequence Returns a sequence containing a default value if the input sequence
is empty; otherwise returns the input sequence.
|
|
public |
Returns the distinct elements in the sequence (removes duplication).
|
|
public |
Returns the element at the specified zero-based index.
|
|
public |
elementAtOrDefault(index: number, defaultValue: *): * Returns the element at the specified zero-based index, or a user-
specified default value.
|
|
public |
Returns all elements of the iterable except the ones in `other`.
|
|
public |
Returns the first element of the sequence.
|
|
public |
firstOrDefault(defaultValue: *, matches: function(i: *): boolean): * Returns the first element of a sequence or a user-specified default value.
|
|
public |
groupBy(getKey: *): * |
|
public |
Returns the distinct elements both iterables (this and `other`) contain.
|
|
public |
join(inner: Sequence, getOuterKey: function(i: *): *, getInnerKey: function(i: *): *, transform: function(outer: *, inner: *): *): * Performs a SQL-like join of two iterables.
|
|
public |
Returns the last element of the sequence.
|
|
public |
lastOrDefault(defaultValue: *, matches: function(i: *): boolean): * Returns the last element of a sequence or a user-specified default value.
|
|
public |
Returns the maximum value in the sequence.
|
|
public |
Returns the minimum value in the sequence.
|
|
public |
orderBy(get: *, compare: *): * Returns a new sequence that contains the elements of the original ordered by
the return value of the `get` function.
|
|
public |
orderByDescending(get: *, compare: *): * Returns a new sequence that contains the elements of the original in descending order,
ordered by the return value of the `get` function.
|
|
public |
reverse(): * |
|
public |
Applies the specified transformation to all elements of the
`Sequence`, returning a new `Sequence` of the transformed elements.
|
|
public |
selectMany(getIterable: function(item: *, index: number): Iterable, transform: function(item: *, innerItem: *): *): Sequence Applies the specified transformations to all elements of the
Sequence.
|
|
public |
Returns the only element of the sequence.
|
|
public |
singleOrDefault(defaultValue: *, matches: function(i: *): boolean): * Returns the single element of a sequence or a user-specified default value.
|
|
public |
skip(count: *): * |
|
public |
skipWhile(matches: *): * |
|
public |
Returns the sum of the elements of the sequence.
|
|
public |
take(count: *): * |
|
public |
takeWhile(matches: *): * |
|
public |
toArray(): * |
|
public |
Creates an eagerly evaluated lookup table of keys mapped to iterables
using the key selector and transformation functions specified.
|
|
public |
Returns the distinct elements from both iterables (this and `other`).
|
|
public |
Filters the Sequence by a condition specified.
|
Static Public Methods
public static empty(): Sequence source
Returns an empty Sequence
.
Note:
The Sequence
instance returned by empty
is cached, that is,
it always returns the same instance.
Example:
console.log("start");
for (let i of Sequence.empty()) {
console.log(i);
}
console.log("end");
// Output:
// start
// end
public static range(start: number, count: number): Sequence source
Returns an increasing sequence of integers, of count
items,
starting at start
.
Throw:
if either |
|
if count is negative |
Example:
for (let i of Sequence.range(2, 4)) {
console.log(i);
}
// Output:
// 2
// 3
// 4
// 5
public static repeat(item: *, count: number): Sequence source
Returns a Sequence
that contains the specified element repeated
the specified number of times.
Params:
Name | Type | Attribute | Description |
item | * | The item to be repeated. |
|
count | number | How many times to repeat the item. |
Return:
Sequence | A |
Throw:
if |
|
if |
Example:
for (let i of Sequence.repeat("a", 3)) {
console.log(i);
}
// Output:
// a
// a
// a
Public Constructors
public constructor(The: Iterable) source
Creates a new Sequence
instance wrapping the iterable
specified.
Params:
Name | Type | Attribute | Description |
The | Iterable |
|
Public Members
public iterable: * source
Public Methods
public aggregate(processNext: function(accumulator: *, current: *): *, seed: *, transformResult: function(result: *): *): * source
Applies an aggregation function over the sequence.
Params:
Name | Type | Attribute | Description |
processNext | function(accumulator: *, current: *): * | An aggregation function that gets the accumulated value and the current element of the sequence. |
|
seed | * |
|
The initial value of the accumulator. If it is not specified, the first element of the sequence is used as the seed. |
transformResult | function(result: *): * |
|
A transformation that is applied to the end result of the aggregation. |
Return:
* |
Throw:
if |
|
if |
|
if the sequence is empty and no seed has been specified |
Example:
// Add all numbers in the array. The first one is used as the seed.
const numbers = [1, 2, 3],
sum = from(numbers).aggregate((a, b) => a + b);
console.log(sum); // 6
// Concatenate all strings in the array. Use a seed value.
const animals = ["cat", "dog", "fish", "frog"],
list = from(animals).aggregate((a, b) => a + ", " + b, "Animals: ");
console.log(list); // Animals: cat, dog, fish, frog
// Use a transformation on the result
const animals = ["cat", "dog", "fish", "frog"],
concatNext = (a, b) => a + ", " + b,
prefix = "Animals: ",
makeParagraph = x => "<p>" + x + "</p>",
paragraph = from(animals).aggregate(concatNext, prefix, makeParagraph);
console.log(paragraph);
// Output:
// <p>Animals: cat, dog, fish, frog</p>
public all(matches: function(i: *): boolean): boolean source
Determines whether all elements satisfy a condition.
Throw:
if |
Example:
const numbers = [1, 2, 3],
even = [2, 4, 6],
isEven = n => n % 2 === 0;
from(numbers).all(isEven); // false
from(even).all(isEven); // true
public any(matches: function(i: *): boolean): boolean source
Determines whether at least one element satisfies a condition.
Without a condition, !c.any()
can be used to quickly test whether
a sequence is empty. This is the preferred way of testing emptiness
vs. c.count() === 0
, as it always runs in O(1) time.
Throw:
if |
Example:
// Without a condition, `any` can be used to quickly test whether
// a sequence is empty.
const empty = [],
nonEmpty = [1];
console.log(from(empty).any()); // false
console.log(from(nonEmpty).any()); // true
// With a condition
const numbers = [1, 2, 3],
even = [2, 4, 6],
isOdd = n => n % 2 !== 0;
from(numbers).any(isOdd); // true
from(even).any(isOdd); // false
public average(getValue: function(i: *): *): number source
Calculates the average (arithmetic mean) of the elements of the sequence.
Evaluation: eager
Params:
Name | Type | Attribute | Description |
getValue | function(i: *): * |
|
A function to determine the value to include in the average for the current element. |
Throw:
if |
|
if the sequence is empty. |
Example:
// Fist example: simple average
console.log(
from([1, 2, 3]).average()
);
// Output: 2
// Second example: using the `getValue` function
const employees = [
{ id: 1, salary: 20000 },
{ id: 2, salary: 30000 },
{ id: 3, salary: 40000 }
];
console.log(
from(employees).average(emp => emp.salary);
);
// Output: 30000
public concat(other: Iterable): Sequence source
Concatenates the iterable specified with the current one.
Params:
Name | Type | Attribute | Description |
other | Iterable | The iterable to concatenate after this instance. |
Example:
const numbers = [1, 2],
letters = ["a", "b"],
result = from(numbers).concat(letters);
for (let i of result) {
console.log(i); // 1 2 a b
}
public contains(item: *): boolean source
Determines whether at least one element is equal to the item specified using the strict equality operator.
Params:
Name | Type | Attribute | Description |
item | * | The item to find. |
Example:
const numbers = [1, 2, 3];
from(numbers).contains(n => n % 2 === 0); // true, 2 is even
from(numbers).contains(n => n > 3); // false, all elements less than 3
public count(matches: function(item: *): boolean): number source
Returns the number of elements in the Sequence
.
If a matches
function is specified, returns the number of matching
elements.
Note: To quickly test whether a sequence is empty, use !c.any()
instead
of .count() === 0
as the former always runs in O(1) time.
Complexity:
- O(1) if the
Iterable
wrapped by thisSequence
is anArray
,Map
orSet
- O(n) for other
Iterable
s
Note: The complexity is O(1) only if the Array
, Map
or Set
is wrapped
directly, like from([1, 2]).count()
. Indirect wrapping will cause the entire
sequence to be iterated, as it is the case for
from([1, 2]).where(n => n % 2 === 0).count()
.
Throw:
if |
Example:
// No condition specified
const numbers = [1, 2, 3, 4],
isEven = n => n % 2 === 0,
count = from(numbers).count();
console.log(count); // 4
// Count matching elements
const numbers = [1, 2, 3, 4],
isEven = n => n % 2 === 0,
numberOfEvens = from(numbers).count(isEven);
console.log(numberOfEvens); // 2
public defaultIfEmpty(defaultValue: *): Sequence source
Returns a sequence containing a default value if the input sequence is empty; otherwise returns the input sequence.
Evaluation: lazy
Params:
Name | Type | Attribute | Description |
defaultValue | * |
|
if the input sequence is empty, the result is a sequence containing this value. |
Return:
Sequence | a sequence containing a default value if the input sequence is empty; otherwise the input sequence. |
Example:
// If the input sequence is not empty, the result is the original
// sequence
const ex1 = from([1, 2]).defaultIfEmpty();
for (let i of ex1) {
console.log(i);
}
// Output:
// 1
// 2
// If the input sequence is empty, the result is a sequence containing
// one `undefined` value
const ex2 = from([]).defaultIfEmpty();
for (let i of ex2) {
console.log(i);
}
// Output:
// undefined
// If the input sequence is empty and a default value is specified,
// the result is a sequence the only item of which is the default value
const ex3 = from([]).defaultIfEmpty(0);
for (let i of ex2) {
console.log(i);
}
// Output:
// 0
public distinct(): Sequence source
Returns the distinct elements in the sequence (removes duplication).
Example:
const numbers = [1, 1, 1, 2, 3, 4, 3],
noDupl = from(numbers).distinct();
for (let n of noDupl) console.log(n); // 1 2 3 4
public elementAt(index: number): * source
Returns the element at the specified zero-based index.
Evaluation: eager
Complexity: O(1) for Array
s, O(n) for other iterables.
Params:
Name | Type | Attribute | Description |
index | number | The non-negative integer index of the element to return. |
Return:
* | The element of the sequence at the specified index. |
Throw:
if |
Example:
const numbers = [1, 2, 3];
console.log(from(numbers).elementAt(2)); // Output: 3
public elementAtOrDefault(index: number, defaultValue: *): * source
Returns the element at the specified zero-based index, or a user- specified default value.
Evaluation: eager
Complexity: O(1) for Array
s, O(n) for other iterables.
Params:
Name | Type | Attribute | Description |
index | number | The non-negative integer index of the element to return. |
|
defaultValue | * |
|
The default value to return if the index is
out of bounds. If not specified, |
Return:
* | The element of the sequence at the specified index, or the default value if the index is out of bounds of the sequence. |
Throw:
if |
Example:
const numbers = [1, 2, 3];
console.log(from(numbers).elementAtOrDefault(2)); // Output: 3
console.log(from(numbers).elementAtOrDefault(3)); // Output: undefined
console.log(from(numbers).elementAtOrDefault(false)); // Output: false
public except(other: Iterable): Sequence source
Returns all elements of the iterable except the ones in other
.
Params:
Name | Type | Attribute | Description |
other | Iterable | The iterable to be subtracted. |
Throw:
Example:
const numbers = [1, 2, 3, 4, 5],
exceptions = [3, 4],
difference = from(numbers).except(exceptions);
for (let n of difference) console.log(n); // 1 2 5
public first(matches: function(i: *): boolean): * source
Returns the first element of the sequence. If a matches
function
is specified, it returns the first matching element.
Evaluation: eager
Return:
* | The first (matching) element. |
Throw:
if |
|
if the sequence contains no elements or no matching element has been found. |
Example:
// No condition specified, simply retrieve the first element of
// the sequence:
const numbers = [1, 2, 3, 4, 5],
first = from(numbers).first();
console.log(first); // 1
// Getting the first element that matches a condition:
const numbers = [1, 2, 3, 4, 5],
firstEven = from(numbers).first(n => n % 2 === 0);
console.log(firstEven); // 2
public firstOrDefault(defaultValue: *, matches: function(i: *): boolean): * source
Returns the first element of a sequence or a user-specified default value.
If a matches
function is specified, it returns the first matching
element or the default value.
Evaluation: eager
Return:
* | The first (matching) element of the sequence or the default value. |
Throw:
if |
Example:
// Get first element of a non-empty sequence
const numbers = [1, 2, 3];
console.log(from(numbers).firstOrDefault()); // Output: 1
// Try to get first element of an empty sequence. No default value specified.
console.log(from([]).firstOrDefault()); // Output: undefined
// Try to get first element of an empty sequence. 0 is specified as a default.
console.log(from([]).firstOrDefault(0)); // Output: 0
// Get first matching element of a sequence with matching elements
const numbers = [1, 2, 3, 4];
console.log(from(numbers).firstOrDefault(0, n => n % 2 === 0)); // Output: 2
// Get first matching element of a sequence without a matching element
const numbers = [1, 3, 5];
console.log(from(numbers).firstOrDefault(0, n => n % 2 === 0)); // Output: 0
public intersect(other: Iterable): Sequence source
Returns the distinct elements both iterables (this and other
) contain.
Params:
Name | Type | Attribute | Description |
other | Iterable | The iterable to intersect the current one with. |
Throw:
if |
Example:
const a = [1, 2, 3],
b = [2, 3, 4, 3],
i = from(a).intersect(b);
for (let n of i) console.log(i); // 2 3
public join(inner: Sequence, getOuterKey: function(i: *): *, getInnerKey: function(i: *): *, transform: function(outer: *, inner: *): *): * source
Performs a SQL-like join of two iterables.
The getOuterKey
and getInnerKey
functions are used to determine the
join key for an element of the outer and the inner sequence, respectively.
The resulting pairs of elements can be transformed using the optional
transform
function. If transform
is not specified, join
returns a
sequence of two-element arrays where the element at index 0 is from the
first sequence and the one at index 1 is from the second.
Params:
Name | Type | Attribute | Description |
inner | Sequence | The inner sequence. |
|
getOuterKey | function(i: *): * | Returns the join key to be used for the current element of the outer sequence. |
|
getInnerKey | function(i: *): * | Returns the join key to be used for the current element of the inner sequence. |
|
transform | function(outer: *, inner: *): * |
|
A transformation to be applied to the resulting pairs of elements. |
Return:
* | If |
Throw:
if |
Example:
const users = [
{ id: 1, name: "Jane Smith" },
{ id: 2, name: "John Smith" },
{ id: 3, name: "Mary Brown" }
];
const emails = [
{ user_id: 1, address: "[email protected]" },
{ user_id: 1, address: "[email protected]" },
{ user_id: 3, address: "[email protected]" }
];
//
// First example: no `transform` function
//
const usersWithEmails =
from(users)
.join(emails, user => user.id, email => email.user_id);
for (let uwe of usersWithEmails) {
console.log(uwe[0].name + ": " + uwe[1]);
}
// Output:
// Jane Smith: [email protected]
// Jane Smith: [email protected]
// Mary Brown: [email protected]
//
// Second example: using a `transform` function
//
const userNamesWithEmails =
from(users)
.join(emails,
user => user.id,
email => email.user_id,
(user, email) => user.name + ": " + email.address);
for (let uwe of userNamesWithEmails) {
console.log(uwe);
}
// Output:
// Jane Smith: [email protected]
// Jane Smith: [email protected]
// Mary Brown: [email protected]
public last(matches: function(i: *): boolean): * source
Returns the last element of the sequence. If a matches
function
is specified, it returns the last matching element.
Evaluation: eager
Return:
* | The last (matching) element. |
Throw:
if |
|
if the sequence contains no elements or no matching element has been found. |
Example:
// No condition specified, simply retrieve the last element of
// the sequence:
const numbers = [1, 2, 3, 4, 5],
last = from(numbers).last();
console.log(last); // 5
// Getting the last element that matches a condition:
const numbers = [1, 2, 3, 4, 5],
lastEven = from(numbers).last(n => n % 2 === 0);
console.log(lastEven); // 4
public lastOrDefault(defaultValue: *, matches: function(i: *): boolean): * source
Returns the last element of a sequence or a user-specified default value.
If a matches
function is specified, it returns the last matching
element or the default value.
Evaluation: eager
Return:
* | The last (matching) element of the sequence or the default value. |
Throw:
if |
Example:
// Get last element of a non-empty sequence
const numbers = [1, 2, 3];
console.log(from(numbers).lastOrDefault()); // Output: 3
// Try to get last element of an empty sequence. No default value specified.
console.log(from([]).lastOrDefault()); // Output: undefined
// Try to get last element of an empty sequence. 0 is specified as a default.
console.log(from([]).lastOrDefault(0)); // Output: 0
// Get last matching element of a sequence with matching elements
const numbers = [1, 2, 3, 4];
console.log(from(numbers).lastOrDefault(0, n => n % 2 === 0)); // Output: 4
// Get last matching element of a sequence without a matching element
const numbers = [1, 3, 5, 7];
console.log(from(numbers).lastOrDefault(0, n => n % 2 === 0)); // Output: 0
public max(transform: function(i: *): *, compare: function(a: *, b: *): number): * source
Returns the maximum value in the sequence.
If a transform
function is specified, the transformation is invoked
for each element of the sequence and the maximum of the transformed
values is returned. By default, max
uses the standard ECMAScript
<
and >
operators for comparison, but that behavior can be
customized by specifying a compare
function.
Evaluation: eager
Params:
Name | Type | Attribute | Description |
transform | function(i: *): * |
|
A transformation to be applied to each element of the sequence. If specified, the maximum of the transformed values is returned. |
compare | function(a: *, b: *): number |
|
A function that returns a negative number if its first argument is less than the second, a positive number if its first argument is greater than the second, otherwise, 0. |
Return:
* | The maximum value in the sequence. |
Throw:
if either |
|
if the sequence is empty. |
Example:
// Called with no arguments
const numbers = [20, 35, -12, 0, 4, -7];
console.log(from(numbers).max()); // Output: 35
// Using a transformation
const people = [
{ name: "Jennifer", age: 23 },
{ name: "John", age: 33 },
{ name: "Jack", age: 42 },
{ name: "Jill", age: 18 },
{ name: "Bob", age: 20 }
];
console.log(from(people).max(p => p.age));
// Output:
// 42
// Using a transformation and a custom comparer
const people = [
{ name: "Jennifer", age: 23 },
{ name: "John", age: 33 },
{ name: "Jack", age: 42 },
{ name: "Jill", age: 18 },
{ name: "Bob", age: 20 }
];
const compareLength = (a, b) => a.length - b.length;
console.log(
from(people).max(p => p.name, compareLength);
);
// Output:
// "Jennifer"
public min(transform: function(i: *): *, compare: function(a: *, b: *): number): * source
Returns the minimum value in the sequence.
If a transform
function is specified, the transformation is invoked
for each element of the sequence and the minimum of the transformed
values is returned. By default, min
uses the standard ECMAScript
<
and >
operators for comparison, but that behavior can be
customized by specifying a compare
function.
Evaluation: eager
Params:
Name | Type | Attribute | Description |
transform | function(i: *): * |
|
A transformation to be applied to each element of the sequence. If specified, the minimum of the transformed values is returned. |
compare | function(a: *, b: *): number |
|
A function that returns a negative number if its first argument is less than the second, a positive number if its first argument is greater than the second, otherwise, 0. |
Return:
* | The minimum value in the sequence. |
Throw:
if either |
|
if the sequence is empty. |
Example:
// Called with no arguments
const numbers = [20, 35, -12, 0, 4, -7];
console.log(from(numbers).min()); // Output: -12
// Using a transformation
const people = [
{ name: "Jennifer", age: 23 },
{ name: "John", age: 33 },
{ name: "Jack", age: 42 },
{ name: "Jill", age: 18 },
{ name: "Bob", age: 20 }
];
console.log(from(people).min(p => p.age));
// Output:
// 18
// Using a transformation and a custom comparer
const people = [
{ name: "Jennifer", age: 23 },
{ name: "John", age: 33 },
{ name: "Jack", age: 42 },
{ name: "Jill", age: 18 },
{ name: "Bob", age: 20 }
];
const compareLength = (a, b) => a.length - b.length;
console.log(
from(people).min(p => p.name, compareLength);
);
// Output:
// "Bob"
public orderBy(get: *, compare: *): * source
Returns a new sequence that contains the elements of the original ordered by
the return value of the get
function. An optional compare
function can
also be specified to implement custom comparison logic (by default, the
orderBy
operator orders the sequence based on the result of the standard
ECMAScript comparison operators).
Params:
Name | Type | Attribute | Description |
get | * | ||
compare | * |
|
Return:
* |
public orderByDescending(get: *, compare: *): * source
Returns a new sequence that contains the elements of the original in descending order,
ordered by the return value of the get
function. An optional compare
function can
also be specified to implement custom comparison logic (by default, the
orderBy
operator orders the sequence based on the result of the standard
ECMAScript comparison operators).
Params:
Name | Type | Attribute | Description |
get | * | ||
compare | * |
|
Return:
* |
public select(transform: function(item: *, index: number): *): Sequence source
Applies the specified transformation to all elements of the
Sequence
, returning a new Sequence
of the transformed elements.
Throw:
if |
Example:
// Simple case, only the `item` parameter of `matches` is used
const numbers = [1, 2, 3, 4, 5],
even = from(numbers).select(n => n % 2 === 0);
for (let n of even) {
console.log(n); // 2 4
}
// Here we also use the `index` parameter
const numbers = [1, 2, 3, 4, 5],
numbersPlusIndices = from(numbers).select((n, i) => n + i);
for (let n of numbersPlusIndices) {
console.log(n); // 1 3 5 7 9
}
public selectMany(getIterable: function(item: *, index: number): Iterable, transform: function(item: *, innerItem: *): *): Sequence source
Applies the specified transformations to all elements of the Sequence. The first transformation returns an iterable. The second one, if present, is called for each element of the output of the first, and returns an arbitrary value. The result is either a concatenation of the iterables returned by the first transformation, or a sequence containing the values returned by the second.
Params:
Name | Type | Attribute | Description |
getIterable | function(item: *, index: number): Iterable | A
function that returns an iterable for each sequence element. The
first argument, |
|
transform | function(item: *, innerItem: *): * |
|
A function
that is called for each element of the iterables returned by
|
Return:
Sequence | A sequence of the values returned by the composition of the transformation functions. |
Throw:
If the object returned by |
Example:
// Simple example, only the `getIterable` function is used
const taskLists = [
{tasks: [1]}, {tasks: [2, 3]}, {tasks: [4]},
{tasks: []}, {tasks: [5]}
];
const allTasks = from(taskLists).selectMany(t => t.tasks);
for (let t of allTasks) {
console.log(t); // 1 2 3 4 5
}
// Here we use both transformation functions
const tasksByDate = [
{
date: "2015-09-20",
tasks: [
{ id: 1, text: "buy groceries" },
{ id: 2, text: "do laundry" },
{ id: 3, text: "meet Janet" }
]
},
// ... more objects like above ...
];
const allTasks =
from(tasksByDate)
.selectMany(date => date.tasks, (date, task) => task.text);
for (let task of allTasks) {
console.log(task);
}
// Output:
// buy groceries
// do laundry
// meet Janet
// ...
public single(matches: function(i: *): boolean): * source
Returns the only element of the sequence. If a matches
function
is specified, it returns the single matching element.
Evaluation: eager
Note: singleOrDefault
can be used to express that a sequence should
contain at most one (matching) element, and the presence of multiple (matching)
elements is an error.
Return:
* | The single (matching) element. |
Throw:
if |
|
if the sequence contains no elements, if no matching element has been found, if the sequence contains more than one (matching) element. |
Example:
// No condition specified, simply retrieve the only element of
// the sequence:
const numbers = [1],
single = from(numbers).single();
console.log(single); // 1
// Getting the only element that matches a condition:
const numbers = [1, 2, 3],
singleEven = from(numbers).single(n => n % 2 === 0);
console.log(singleEven); // 2
// `single` can be used to express that we expect only one matching
// element when the presence of more than one matching elements is
// a programming error:
// this is expected to contain only one even number
const numbers = [1, 2, 3, 4, 5];
// BOOM! this throws a RangeError because the sequence contains more
// than one matching element
const even = from(numbers).single(even);
public singleOrDefault(defaultValue: *, matches: function(i: *): boolean): * source
Returns the single element of a sequence or a user-specified default value.
If a matches
function is specified, it returns the single matching
element or the default value.
Evaluation: eager
Note: singleOrDefault
can be used to express that a sequence should
contain at most one (matching) element, and the presence of multiple (matching)
elements is an error.
Return:
* | The single (matching) element of the sequence or the default value. |
Throw:
if |
|
if the sequence contains more than one matching element |
Example:
// Get the only element of a non-empty sequence
const numbers = [1];
console.log(from(numbers).singleOrDefault()); // Output: 1
// Try to get the single element of an empty sequence. No default value specified.
console.log(from([]).singleOrDefault()); // Output: undefined
// Try to get single element of an empty sequence. 0 is specified as a default.
console.log(from([]).singleOrDefault(0)); // Output: 0
// Get single matching element of a sequence with matching elements
const numbers = [1, 2, 3];
console.log(from(numbers).singleOrDefault(0, n => n % 2 === 0)); // Output: 2
// Get last matching element of a sequence without a matching element
const numbers = [1, 3, 5, 7];
console.log(from(numbers).singleOrDefault(0, n => n % 2 === 0)); // Output: 0
// Get single matching element of a sequence with multiple matching elements
const numbers = [1, 2, 3, 4];
// BOOM! This throws a `RangeError`:
console.log(from(numbers).singleOrDefault(0, n => n % 2 === 0));
public sum(getValue: function(i: *): number): * source
Returns the sum of the elements of the sequence. If a getValue
function is specified, it is called for each element of the
sequence, and the return values are summed.
Return:
* | The sum of the (matching) elements. |
Throw:
if the value returned by |
Example:
// Without `getValue`
console.log(
from([1, 2, 3]).sum()
);
// Output: 6
// With `getValue`
const employees = [
{ name: "John Smith", salary: 15000 },
{ name: "Jane Smith", salary: 26000 },
{ name: "Jane Doe", salary: 15000 },
];
const totalSalary = from(employees).sum(emp => emp.salary);
console.log(totalSalary); // 56000
public toLookup(getKey: function(item: *): *, transform: function(item: *): *): * source
Creates an eagerly evaluated lookup table of keys mapped to iterables using the key selector and transformation functions specified.
Evaluation: eager
Note: The difference between toLookup
and groupBy
is that toLookup
uses eager evaluation.
Params:
Name | Type | Attribute | Description |
getKey | function(item: *): * | A function that, given an element, returns the value to use as its key in the lookup table. |
|
transform | function(item: *): * |
|
A function that is called for each element of the sequence and generates the values in the lookup table. |
Return:
* |
Throw:
if either |
Example:
const books = [
{ title: "The Lord of the Rings", author: "J. R. R. Tolkien", category: "fantasy" },
{ title: "Solaris", author: "Stanislaw Lem", category: "sci-fi" },
{ title: "The Hobbit", author: "J. R. R. Tolkien", category: "fantasy" },
{ title: "Rendezvous with Rama", author: "A. C. Clarke", category: "sci-fi" },
{ title: "JavaScript Allongé", author: "Reginald Braithwaithe", category: "non-fiction" }
];
// Only `getKey` used:
let booksByCategory =
from(books)
.toLookup(b => b.category);
for (let {category, books} of booksByCategory) {
console.log(category);
for (let book of books) {
console.log(" " + book.author + " - " + book.title);
}
}
// Output:
// fantasy
// J. R. R. Tolkien - The Lord of the Rings
// J. R. R. Tolkien - The Hobbit
// sci-fi
// Stanislaw Lem - Solaris
// A. C. Clarke - Rendezvous with Rama
// non-fiction
// Reginald Braithwaithe - JavaScript Allongé
// `getKey` and `transform` used:
let booksByCategory =
from(books)
.toLookup(b => b.category, b => b.title);
for (let {category, titles} of booksByCategory) {
console.log(category);
for (let title of titles) {
console.log(" " + title);
}
}
// Output:
// fantasy
// The Lord of the Rings
// The Hobbit
// sci-fi
// Solaris
// Rendezvous with Rama
// non-fiction
// JavaScript Allongé
public union(other: Iterable): Sequence source
Returns the distinct elements from both iterables (this and other
).
Params:
Name | Type | Attribute | Description |
other | Iterable | The iterable to union the current one with. |
Example:
const a = [1, 2, 1, 3, 2],
b = [3, 3, 4, 5, 4],
u = from(a).union(b);
for (let i of u) console.log(i); // 1 2 3 4 5
public where(matches: function(item: *, index: number): boolean): Sequence source
Filters the Sequence by a condition specified.
Throw:
if |
Example:
// Simple case, only the `item` parameter of `matches` is used
const numbers = [1, 2, 3, 4, 5],
even = from(numbers).where(n => n % 2 === 0);
for (let n of even) console.log(n); // 2 4
// Here we also use the `index` parameter
const numbers = [2, 1, 3, 0, 4],
itemEqualsIndex = (item, index) => item === index,
numbersEqualToTheirIndices = from(numbers).where(itemEqualsIndex);
for (let n of numbersEqualToTheirIndices) {
console.log(n); // 1 4
}