eslinq
v0.1.0
Published
An elegant way of working with ES6 iterables
Downloads
7
Readme
ESLinq
An elegant way of working with iterables
ESLinq aims to be a complete, robust, thoroughly tested port of Linq to Objects to ECMAScript 2015 (ES6).
A first example
Problem: We have an array of users. A user can have multiple email addresses, and not all users are verified. We need a list of the email addresses of the verified users, and check if all of them end in ".com".
const users = [
{
"id": 12,
"name": "John Smith",
"emails": ["[email protected]", "[email protected]", "[email protected]"],
"verified": true
},
{
"id": 56,
"name": "Jennifer Brown",
"emails": ["[email protected]", "[email protected]"],
"verified": false
},
{
"id": 98,
"name": "Kate Newton",
"emails": ["[email protected]", "[email protected]"],
"verified": true
}
];
First, we need to restrict the list to only contain verified users:
const verifiedUsers = from(users).where(user => user.verified);
Then, we need to get a concatenated list of the email addresses of verified users:
const verifiedUserEmails =
from(users)
.where(user => user.verified)
.selectMany(user => user.emails);
It is important to note that verifiedUserEmails
is a lazily evaluated iterable: filtering
and transformation is only done once we start iterating it, e. g. with a for..of
loop:
for (let email of verifiedUserEmails) {
// The first time this loop executes is the first time the original iterable is read from.
// Filtering (`where`) and transformation (`selectMany`) run element-by-element during iteration.
console.log(email);
}
Now let's check if all emails end with ".com":
const allEmailsEndWithCom =
from(users)
.where(user => user.verified)
.selectMany(user => user.emails)
.all(email => email.endsWith(".com"));
The result is a bool value indicating whether all emails end with the substring ".com". The all
operator is an eager one: it iterates through all elements to compute its value.