ts-linq 1.0.11
Install from the command line:
Learn more about npm packages
$ npm install @reapptor/ts-linq@1.0.11
Install via package.json:
"@reapptor/ts-linq": "1.0.11"
About this version
It is a complete, fully tested analog of C# Language-Integrated Query (LINQ) written in TypeScript.
LINQ package generally operates on the collection types and comes as extension methods serving a variety of purposes in working with collections of types.
The original idea behind this package is to make TypeScript syntax look like C# to ease the work for developers using both C# and TypeScript in their day-to-day work.
All
Any
Chunk
Count
Distinct
First
FirstOrDefault
Last
LastOrDefault
Max
Min
Repeat
SelectMany
Skip
Sum
Take
TakeLast
TakeWhile
Determines whether all elements of a sequence satisfy a condition.
/**
* @param predicate - A function to test each element for a condition.
* @returns boolean - true if every element of the source sequence passes the test in the specified predicate, or if the sequence is empty; otherwise, false.
*/
all(predicate: (item: T, index: number) => boolean): boolean;
The following code examples demonstrates how to use All to determine whether all the elements in a sequence satisfy a condition. The result is true if every element of the source sequence passes the test in the specified predicate, or if the sequence is empty; otherwise, false.
const numbers: number[] = [1, 2, 3];
const empty: number[] = [];
const allFive: number[] = [5, 5, 5];
const hasAllTwo: boolean = numbers.all(item => item == 2);
console.log("hasAllTwo = ", hasAllTwo);
const hasAllOnEmpty: boolean = empty.all(item => item == 1);
console.log("hasAllOnEmpty = ", hasAllOnEmpty);
const hasAllFive: boolean = allFive.all(item => item == 5);
console.log("hasAllFive = ", hasAllFive);
hasAllTwo = false;
hasAllOnEmpty = true;
hasAllFive = true;
Determines whether a sequence contains any elements in the collection, which satisfies an optional condition. If no condition is provided, the method just returns if the collection is empty or not.
/**
* @param predicate - A function to test each element for a condition.
* @returns boolean - true if every element of the source sequence passes the test in the specified predicate, or if the sequence is empty; otherwise, false.
*/
any(predicate?: (item: T, index: number) => boolean): boolean;
The following code example demonstrates how to use Any to determine whether a sequence contains any elements.
const numbers: number[] = [1, 2, 3];
const empty: number[] = [];
const hasSecond: boolean = numbers.any(item => item == 2);
console.log("hasSecond = ", hasSecond);
const hasFifth: boolean = numbers.any(item => item == 5);
console.log("hasFifth = ", hasFifth);
const hasAnyNumber: boolean = numbers.any();
console.log("hasAnyNumber = ", hasAnyNumber);
const hasEmptyAnyNumber: boolean = empty.any();
console.log("hasEmptyAnyNumber = ", hasEmptyAnyNumber);
hasSecond = true;
hasFifth = false;
hasAny = true;
hasEmptyAnyNumber = false;
Splits the elements of a sequence into chunks of the parameter size at most size.
/**
* @param size - The maximum size of each chunk.
* @returns Array<T>[] - An Array<T> that contains the elements the input sequence split into chunks of size size.
*/
chunk(size: number): T[][];
The following code example demonstrates how to use Chunk on a sequence. Each chunk except the last one will be of size size. The last chunk will contain the remaining elements and may be of a smaller size.
const numbers: number[] = [1, 2, 3, 4];
let size: number = 1;
const chunkedNumbersSize1 = numbers.chunk(size);
console.log("[1, 2, 3, 4] chunk with size of 1 = ", chunkedNumbersSize1);
size = 10;
const chunkedNumbersSize10 = numbers.chunk(size);
console.log("[1, 2, 3, 4] chunk with size of 10 = ", chunkedNumbersSize10);
const empty: number[] = [];
const chunkedOnEmpty = numbers.chunk(size);
console.log("[] chunk with size of 10 = ", chunkedOnEmpty);
[1, 2, 3, 4] chunk with size of 1 = [ [ 1 ], [ 2 ], [ 3 ], [ 4 ] ]
[1, 2, 3, 4] chunk with size of 10 = [ [ 1, 2, 3, 4 ] ]
[] chunk with size of 10 = []
Parameter size is below 1.
const numbers: number[] = [1, 2, 3, 4];
let size: number = 0;
try {
const chunkedNumbers = numbers.chunk(0);
} catch (e: any) {
console.log(e.message);
}
Size "0" out of range, must be at least 1 or greater.
Returns the number of elements in a sequence.
/**
* @param predicate - A function to test each element for a condition.
* @returns number - The number of elements in the input sequence if the predicate is not specified or, otherwise, the number of elements source that passes the test, specified by the predicate.
*/
count(predicate?: ((item: T, index: number) => boolean) | null): number;
The following code example demonstrates how to use Count to count the elements in an array.
const numbers: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const count = numbers.count();
console.log(`There are ${count} numbers in the collection`);
There are 10 numbers in the collection
Returns distinct elements from a sequence.
/**
* @param predicate - A predicate function to get comparable value.
* @returns Array<T> - An Array<T> that contains distinct elements from the source sequence.
*/
distinct(predicate?: ((item: T) => any) | null): T[];
The following code examples demonstrates how to use Count to count the elements in an array.
const values: any[] = [1, 1, "red", 2, 3, 3, 4, "green", 5, 6, 10, "green"];
const distinctValues = values.distinct();
console.log("distinctValues = ", distinctValues);
distinctValues = [ 1, 'red', 2, 3, 4, 'green', 5, 6, 10 ]
class Human {
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
public name: string;
public age: number;
}
const aleks: Human = new Human("Aleks", 23);
const youngJack: Human = new Human("Jack", 14);
const oldJack: Human = new Human("Jack", 64);
const distinctNameHumans = humans.distinct(item => item.name);
console.log("distinctNameHumans = ", distinctNameHumans);
const distinctAgeHumans = humans.distinct(item => item.age);
console.log("distinctAgeHumans = ", distinctAgeHumans);
distinctValues = [ 1, 'red', 2, 3, 4, 'green', 5, 6, 10 ]
distinctNameHumans = [
Human { name: 'Aleks', age: 23 },
Human { name: 'Jack', age: 64 }
]
distinctAgeHumans = [
Human { name: 'Aleks', age: 23 },
Human { name: 'Jack', age: 14 },
Human { name: 'Jack', age: 64 }
]
Returns the first element of a sequence, or a default value if no element is found, or throw error if no default element is not specified.
/**
* @param predicate - A function to test each element for a condition.
* @param defaultValue - The default value to return if the sequence is empty.
* @returns T - defaultValue if source is empty or if no element passes the test specified by predicate; otherwise, the first element in source that passes the test specified by predicate.
*/
first(predicate?: ((item: T) => boolean) | null, defaultValue?: T | null): T;
The following code examples demonstrates how to use First to return the first element of an array that satisfies a condition, first or default.
const numbers: number[] = [ 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19];
const first: number = numbers.first();
console.log("First = ", first);
const numbers: number[] = [ 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19];
const firstGreaterThan80: number = numbers.first(item => item > 80);
console.log("First number in the sequence greater than 80 = ", first);
const numbers: number[] = [ 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19];
const defaultValue: number = numbers.first(item => item == 1, -1);
console.log("Default value = ", defaultValue);
First = 9
First number in the sequence greater than 80 = 92
Default value = -1
Sequence has none elements matching the predicate.
const numbers: number[] = [ 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19];
try {
const firstGreaterThan80: number = numbers.first(item => item == 1);
} catch (e: any) {
console.log(e.message);
}
No item found matching the specified predicate.
Returns the first element of a sequence, or a default value if no element is found.
/**
* @param callback - A function to test each element for a condition.
* @param defaultValue - The default value to return if the sequence is empty.
* @returns T - defaultValue if source is empty or if no element passes the test specified by predicate; otherwise, the first element in source that passes the test specified by predicate.
*/
firstOrDefault(callback?: ((item: T) => boolean) | null, defaultValue?: T | null): T | null;
The following code examples demonstrates how to use FirstOrDefault to return the first element of an array that satisfies a condition or a default value if the defaultValue parameter is specified, otherwise null.
const numbers: number[] = [ 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19];
const firstInSequence: number | null = numbers.firstOrDefault();
console.log("First in the sequence = ", firstInSequence);
const numbers: number[] = [ 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19];
const firstMatching: number | null = numbers.firstOrDefault(item => item > 435);
console.log("First in the sequence that is greater than 400 = ", firstMatching);
const numbers: number[] = [ 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19];
const defaultIfNotFound: number = numbers.firstOrDefault(item => item == -1);
console.log("None of the items matching the predicate. The return value = ", defaultIfNotFound);
const numbers: number[] = [ 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19];
const defaultProvidedIfNotFound: number = numbers.firstOrDefault(item => item > 1000, -1);
console.log("Default value is -1 if none of the elements matching the predicate. The return value = ", defaultProvidedIfNotFound);
First in the sequence = 9
First in the sequence that is greater than 400 = 435
None of the items matching the predicate. The return value = null
Return -1 if none of the elements matching the predicate. The return value = -1
Returns the last element of a sequence, or a default value if no element is found, or throw error if no default element is not specified.
/**
* @param predicate - A function to test each element for a condition.
* @param defaultValue - The default value to return if the sequence is empty.
* @returns T - defaultValue if source is empty or if no element passes the test specified by predicate; otherwise, the last element in source that passes the test specified by predicate.
*/
last(predicate?: ((item: T) => boolean) | null, defaultValue?: T | null): T;
The following code example demonstrates how to use Last to return the last element of an array that satisfies a condition, last or default.
const numbers: number[] = [ 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19];
const last: number = numbers.last();
console.log("Last = ", last);
const numbers: number[] = [ 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19];
const lastGreaterThan80: number = numbers.last(item => item > 80);
console.log("Last number in the sequence greater than 80 = ", last);
const numbers: number[] = [ 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19];
const defaultValue: number = numbers.last(item => item == 1, -1);
console.log("Default value = ", defaultValue);
Last = 19
Last number in the sequence greater than 80 = 435
Default value = -1
Sequence has none elements matching the predicate.
const numbers: number[] = [ 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19];
try {
const lastGreaterThan80: number = numbers.last(item => item == 1);
} catch (e: any) {
console.log(e.message);
}
No item found matching the specified predicate.
Returns the last element of a sequence, or a specified default value if the sequence contains no elements.
/**
* @param predicate - A function to test each element for a condition.
* @param defaultValue - The default value to return if the sequence is empty.
* @returns T - defaultValue if source is empty or if no element passes the test specified by predicate; otherwise, the last element in source that passes the test specified by predicate.
*/
lastOrDefault(predicate?: ((item: T) => boolean) | null, defaultValue?: T | null): T | null;
The following code examples demonstrates how to use LastOrDefault to return the last element of an array that satisfies a condition or a default value if the defaultValue parameter is specified, otherwise null.
const numbers: number[] = [ 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19];
const lastInSequence: number | null = numbers.lastOrDefault();
console.log("Last in the sequence = ", lastInSequence);
const numbers: number[] = [ 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19];
const lastMatching: number | null = numbers.lastOrDefault(item => item > 435);
console.log("Last in the sequence that is greater than 400 = ", lastMatching);
const numbers: number[] = [ 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19];
const defaultIfNotFound: number = numbers.lastOrDefault(item => item == -1);
console.log("None of the items matching the predicate. The return value = ", defaultIfNotFound);
const numbers: number[] = [ 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19];
const defaultProvidedIfNotFound: number = numbers.lastOrDefault(item => item > 1000, -1);
console.log("Default value is -1 if none of the elements matching the predicate. The return value = ", defaultProvidedIfNotFound);
Last in the sequence = 19
Last in the sequence that is greater than 400 = 435
None of the items matching the predicate. The return value = null
Return -1 if none of the elements matching the predicate. The return value = -1
Returns the maximum value in a sequence of values.
/**
* @param predicate - A function to test each element for a condition.
* @returns T - The maximum value in the sequence.
*/
max(predicate: ((item: T) => number) | null): T;
The following code example demonstrates how to use Max to determine the maximum value in a sequence.
const values: any[] = [null, 1.5E+104, 9E+103, -2E+103];
const max = values.max();
console.log(`The largest number is ${max}`);
The largest number is 1.5e+104
Returns the minimum value in a sequence of values.
/**
* @param predicate - A function to test each element for a condition.
* @returns T - The minimum value in the sequence.
*/
min(predicate: ((item: T) => number) | null): T;
The following code example demonstrates how to use Min to determine the minimum value in a sequence.
const grades: any[] = [78, 92, null, 99, 37, 81];
const min = values.min();
console.log(`The lowest grade is ${min}`);
The lowest grade is 37
Generates a sequence that contains one repeated value.
/**
* @param element - The value to be repeated.
* @param count - The number of times to repeat the value in the generated sequence.
* @returns T[] - An Array<T> that contains a repeated value.
*/
repeat(element: T, count: number): T[];
The following code example demonstrates how to use Repeat to generate a sequence of a repeated value.
const values: string[] = Array.prototype.repeat("I like programming.", 5);
for (let i = 0; i < values.length; i ++) {
console.log(values[i]);
}
I like programming.
I like programming.
I like programming.
I like programming.
I like programming.
Projects each element of a sequence to an Array and flattens the resulting sequences into one sequence.
/**
* @param collectionSelector - A transform function to apply to each element of the input sequence.
* @returns Array<TOut> - An Array<TOut> whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of source and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
selectMany<TOut>(collectionSelector: (item: T) => TOut[]): TOut[];
The following code example demonstrates how to use SelectMany to perform a one-to-many projection over an array.
class PetOwner
{
constructor(name: string, pets: string[]) {
this.name = name;
this.pets = pets;
}
public name: string;
public pets: string[];
}
const higa = new PetOwner("Higa", ["Scruffy", "Sam"]);
const ashkenazi = new PetOwner("Ashkenazi", ["Walker", "Sugar"]);
const price = new PetOwner("Price", ["Scratches", "Diesel"]);
const hines = new PetOwner("Hines", ["Dusty"]);
const petOwners: PetOwner[] = [higa, ashkenazi, price, hines];
const query = petOwners
.selectMany(petOwner => petOwner.pets)
.where(ownerAndPet => ownerAndPet.startsWith("S"));
console.log(query);
[ 'Scruffy', 'Sam', 'Sugar', 'Scratches' ]
Bypasses a specified number of elements in a sequence and then returns the remaining elements.
/**
* @param count - A function to test each element for a condition.
* @returns Array<T> - An Array<T> that contains the elements that occur after the specified index in the input sequence.
*/
skip(count: number): T[];
The following code example demonstrates how to use Skip to skip a specified number of elements in a sorted array and return the remaining elements.
const grades: number[] = [ 59, 82, 70, 56, 92, 98, 85 ];
grades.order(item => item);
const skipped3Grades: number[] = grades.skip(3);
console.log("All grades except the top three are:", skippedGrades);
All grades except the top three are: [ 82, 85, 92, 98 ]
Computes the sum of a sequence of numeric values.
/**
* @param predicate - A function to test each element for a condition.
* @returns number - The sum of the values in the sequence.
*/
sum(predicate: (item: T) => number | null | undefined): number;
The following code example demonstrates how to use Sum to sum the values of a sequence.
const grades: number[] = [ 43.68, 1.25, 583.7, 6.5 ];
const sum: number = grades.sum(item => item);
console.log(`The sum of the numbers is ${sum}.`);
The sum of the numbers is 635.13.
Returns a specified number of contiguous elements from the start of a sequence.
/**
* @param count - The number of elements to return.
* @returns Array<T> - An Array<T> that contains the specified number of elements from the start of the input sequence.
*/
take(count: number): T[];
The following code example demonstrates how to use Take to return elements from the start of a sequence.
const grades: number[] = [ 59, 82, 70, 56, 92, 98, 85 ];
grades.sort((a, b) => b - a);
const top3Grades: number[] = grades.take(3);
console.log(`The top three grades are:${top3Grades}`);
The top three grades are:98,92,85
Returns a new array that contains the last count elements from source.
/**
* @param count - The number of elements to take from the end of the collection.
* @returns Array<T> - A new array that contains the last count elements from source.
*/
takeLast(count: number): T[];
The following code example demonstrates how to use TakeLast to return elements from the start of a sequence.
const grades: number[] = [ 59, 82, 70, 56, 92, 98, 85 ];
grades.sort((a, b) => b - a);
const worst3Grades: number[] = grades.takeLast(3);
console.log(`The worst three grades are:${worst3Grades}`);
The worst three grades are:70,59,56
Returns elements from an array as long as a specified condition is true.
/**
* @param predicate - A function to test each element for a condition.
* @returns Array<T> - An new array that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
takeWhile(predicate: (item: T, index: number) => boolean): T[];
The following code example demonstrates how to use TakeWhile to return elements from the start of a sequence as long as a condition is true.
const fruits: string[] = [ "apple", "banana", "mango", "orange", "passionfruit", "grape" ];
const query = fruits.takeWhile(fruit => fruit != "orange");
console.log(query);
[ 'apple', 'banana', 'mango' ]