Home Reference Source Repository
import {Sequence} from 'eslinq/src/eslinq.js'
public class | source

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

range(start: number, count: number): Sequence

Returns an increasing sequence of integers, of `count` items, starting at `start`.
public static

repeat(item: *, count: number): Sequence

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

Method Summary

Public Methods
public

aggregate(processNext: function(accumulator: *, current: *): *, seed: *, transformResult: function(result: *): *): *

Applies an aggregation function over the sequence.
public

all(matches: function(i: *): boolean): boolean

Determines whether all elements satisfy a condition.
public

any(matches: function(i: *): boolean): boolean

Determines whether at least one element satisfies a condition.
public

average(getValue: function(i: *): *): number

Calculates the average (arithmetic mean) of the elements of the sequence.
public

concat(other: Iterable): Sequence

Concatenates the iterable specified with the current one.
public

contains(item: *): boolean

Determines whether at least one element is equal to the item specified using the strict equality operator.
public

count(matches: function(item: *): boolean): number

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

elementAt(index: number): *

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

except(other: Iterable): Sequence

Returns all elements of the iterable except the ones in `other`.
public

first(matches: function(i: *): boolean): *

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

intersect(other: Iterable): Sequence

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

last(matches: function(i: *): boolean): *

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

max(transform: function(i: *): *, compare: function(a: *, b: *): number): *

Returns the maximum value in the sequence.
public

min(transform: function(i: *): *, compare: function(a: *, b: *): number): *

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

select(transform: function(item: *, index: number): *): Sequence

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

single(matches: function(i: *): boolean): *

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

sum(getValue: function(i: *): number): *

Returns the sum of the elements of the sequence.
public

take(count: *): *

public

takeWhile(matches: *): *

public

toArray(): *

public

toLookup(getKey: function(item: *): *, transform: function(item: *): *): *

Creates an eagerly evaluated lookup table of keys mapped to iterables using the key selector and transformation functions specified.
public

union(other: Iterable): Sequence

Returns the distinct elements from both iterables (this and `other`).
public

where(matches: function(item: *, index: number): boolean): Sequence

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.

Return:

Sequence

A Sequence that has no elements.

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.

Params:

NameTypeAttributeDescription
start number

The first element of the sequence.

count number

The number of elements.

Return:

Sequence

An increasing sequence of integers, of count items, starting at start.

Throw:

TypeError

if either start or count is not a number

RangeError

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:

NameTypeAttributeDescription
item *

The item to be repeated.

count number

How many times to repeat the item.

Return:

Sequence

A Sequence that contains the specified element repeated the specified number of times.

Throw:

TypeError

if count is not a number

RangeError

if count is negative

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:

NameTypeAttributeDescription
The Iterable

Iterable to wrap.

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:

NameTypeAttributeDescription
processNext function(accumulator: *, current: *): *

An aggregation function that gets the accumulated value and the current element of the sequence.

seed *
  • optional

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: *): *
  • optional

A transformation that is applied to the end result of the aggregation.

Return:

*

Throw:

TypeError

if process is not a function

TypeError

if transformResult is specified but is not a function

RangeError

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.

Params:

NameTypeAttributeDescription
matches function(i: *): boolean

A function that determines whether an element of the Sequence satisfies a condition.

Return:

boolean

true if all elements satisfy the condition, otherwise, false.

Throw:

TypeError

if matches is not a function

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.

Params:

NameTypeAttributeDescription
matches function(i: *): boolean

A function that determines whether an element of the Sequence satisfies a condition.

Return:

boolean

true if at least one element satisfies the condition, otherwise, false.

Throw:

TypeError

if matches is not a function

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:

NameTypeAttributeDescription
getValue function(i: *): *
  • optional

A function to determine the value to include in the average for the current element.

Return:

number

The average of the elements.

Throw:

TypeError

if getValue is not a function. If the current element, or if getValue is used, the value returned by it, is not a number.

RangeError

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:

NameTypeAttributeDescription
other Iterable

The iterable to concatenate after this instance.

Return:

Sequence

The concatenation of the two iterables.

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:

NameTypeAttributeDescription
item *

The item to find.

Return:

boolean

true if at least one element is equal to the item specified, otherwise, false.

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 this Sequence is an Array, Map or Set
  • O(n) for other Iterables

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().

Params:

NameTypeAttributeDescription
matches function(item: *): boolean

A function that should return true for all elements to be included in the count and false for those to be excluded.

Return:

number

The number of matching elements in the Sequence.

Throw:

TypeError

if matches is specified, but it is not a function.

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:

NameTypeAttributeDescription
defaultValue *
  • optional

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).

Return:

Sequence

A Sequence containing the distinct elements of the original one.

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 Arrays, O(n) for other iterables.

Params:

NameTypeAttributeDescription
index number

The non-negative integer index of the element to return.

Return:

*

The element of the sequence at the specified index.

Throw:

RangeError

if index is negative. If index is too large.

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 Arrays, O(n) for other iterables.

Params:

NameTypeAttributeDescription
index number

The non-negative integer index of the element to return.

defaultValue *
  • optional

The default value to return if the index is out of bounds. If not specified, undefined is used as the default.

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:

RangeError

if index is negative. If index is too large.

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:

NameTypeAttributeDescription
other Iterable

The iterable to be subtracted.

Return:

Sequence

All elements of the iterable except the ones in other.

Throw:

TypeError

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

Params:

NameTypeAttributeDescription
matches function(i: *): boolean
  • optional

A function that returns true if an element satisfies a condition, false otherwise.

Return:

*

The first (matching) element.

Throw:

TypeError

if matches is not a function

RangeError

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

Params:

NameTypeAttributeDescription
defaultValue *
  • optional
  • default: undefined

The default value to return if the sequence contains no (matching) elements.

matches function(i: *): boolean
  • optional

A function that returns true if an element satisfies a condition, false otherwise.

Return:

*

The first (matching) element of the sequence or the default value.

Throw:

TypeError

if matches is not a function

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 groupBy(getKey: *): * source

Params:

NameTypeAttributeDescription
getKey *

Return:

*

public intersect(other: Iterable): Sequence source

Returns the distinct elements both iterables (this and other) contain.

Params:

NameTypeAttributeDescription
other Iterable

The iterable to intersect the current one with.

Return:

Sequence

The elements both iterables contain.

Throw:

TypeError

if other is not iterable.

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:

NameTypeAttributeDescription
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: *): *
  • optional

A transformation to be applied to the resulting pairs of elements.

Return:

*

If transform is not specified, 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. If transform is specified, a sequence of the output of transform applied to the outer and inner elements.

Throw:

TypeError

if inner is not iterable. If either getOuterKey or getInnerKey is not a function. If transform is specified but it is not a function.

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

Params:

NameTypeAttributeDescription
matches function(i: *): boolean
  • optional

A function that returns true if an element satisfies a condition, false otherwise.

Return:

*

The last (matching) element.

Throw:

TypeError

if matches is not a function

RangeError

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

Params:

NameTypeAttributeDescription
defaultValue *
  • optional
  • default: undefined

The default value to return if the sequence contains no (matching) elements.

matches function(i: *): boolean
  • optional

A function that returns true if an element satisfies a condition, false otherwise.

Return:

*

The last (matching) element of the sequence or the default value.

Throw:

TypeError

if matches is not a function

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:

NameTypeAttributeDescription
transform function(i: *): *
  • optional

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
  • optional

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:

TypeError

if either transform or compare is not a function.

RangeError

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:

NameTypeAttributeDescription
transform function(i: *): *
  • optional

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
  • optional

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:

TypeError

if either transform or compare is not a function.

RangeError

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:

NameTypeAttributeDescription
get *
compare *
  • optional
  • default: compareDefault

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:

NameTypeAttributeDescription
get *
compare *
  • optional
  • default: compareDefault

Return:

*

public reverse(): * source

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.

Params:

NameTypeAttributeDescription
transform function(item: *, index: number): *

A function that is used to transform the elements of the sequence. The first argument, item, is the current sequence element, the second one, index, is the zero-based index of the current element.

Return:

Sequence

A new Sequence of the transformed elements.

Throw:

TypeError

if transform is not a function

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:

NameTypeAttributeDescription
getIterable function(item: *, index: number): Iterable

A function that returns an iterable for each sequence element. The first argument, item, is the current sequence element, the second one, index, is the zero-based index of the current element.

transform function(item: *, innerItem: *): *
  • optional

A function that is called for each element of the iterables returned by getIterable. The final sequence contains the output of this function. The first argument, item, is the current item of the original sequence, the second, innerItem, is the current element of the iterable returned by getIterable.

Return:

Sequence

A sequence of the values returned by the composition of the transformation functions.

Throw:

Error

If the object returned by getIterable is not iterable.

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.

Params:

NameTypeAttributeDescription
matches function(i: *): boolean
  • optional

A function that returns true if an element satisfies a condition, false otherwise.

Return:

*

The single (matching) element.

Throw:

TypeError

if matches is not a function

RangeError

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.

Params:

NameTypeAttributeDescription
defaultValue *
  • optional
  • default: undefined

The default value to return if the sequence contains no (matching) elements.

matches function(i: *): boolean
  • optional

A function that returns true if an element satisfies a condition, false otherwise.

Return:

*

The single (matching) element of the sequence or the default value.

Throw:

TypeError

if matches is not a function

RangeError

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 skip(count: *): * source

Params:

NameTypeAttributeDescription
count *

Return:

*

public skipWhile(matches: *): * source

Params:

NameTypeAttributeDescription
matches *

Return:

*

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.

Params:

NameTypeAttributeDescription
getValue function(i: *): number
  • optional

A function that returns the term to be summed for the current sequence element.

Return:

*

The sum of the (matching) elements.

Throw:

TypeError

if the value returned by getValue is not a number.

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 take(count: *): * source

Params:

NameTypeAttributeDescription
count *

Return:

*

public takeWhile(matches: *): * source

Params:

NameTypeAttributeDescription
matches *

Return:

*

public toArray(): * source

Return:

*

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:

NameTypeAttributeDescription
getKey function(item: *): *

A function that, given an element, returns the value to use as its key in the lookup table.

transform function(item: *): *
  • optional

A function that is called for each element of the sequence and generates the values in the lookup table.

Return:

*

Throw:

TypeError

if either getKey or transform is not a function

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:

NameTypeAttributeDescription
other Iterable

The iterable to union the current one with.

Return:

Sequence

The distinct elements from both iterables.

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.

Params:

NameTypeAttributeDescription
matches function(item: *, index: number): boolean

A function that returns true if an element is to be included in the result. The first argument, item, is the current sequence element, the second one, index, is the zero-based index of the current element.

Return:

Sequence

A Sequence of the elements for which the 'matches' function returned true.

Throw:

TypeError

if matches is not a function

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
}