Skip to content

Instantly share code, notes, and snippets.

@truseed
Created September 21, 2016 10:30
Show Gist options
  • Save truseed/694da984f8a811b5fe4f6418d0ff1ae2 to your computer and use it in GitHub Desktop.
Save truseed/694da984f8a811b5fe4f6418d0ff1ae2 to your computer and use it in GitHub Desktop.
Linq implementation in ES6
let linq = function*(array){
for (let item of array){
yield item;
}
};
let where = function*(predicate){
for(let item of this){
if (predicate(item)) {
yield item;
}
}
};
let select = function*(transform){
for (let item of this){
yield transform(item);
}
};
let to_array = function(){
return [...this];
};
let linqable = {where, select, to_array};
Object.assign(linq.prototype, linqable);
Object.assign(where.prototype, linqable);
Object.assign(select.prototype, linqable);
Array.prototype.as_queryable = function(){
return linq(this);
}
let employees = [
{ name: 'Sam', age: 55 },
{ name: 'John', age: 27 },
{ name: 'Jessica', age: 30 },
{ name: 'Frodo', age: 34 },
{ name: 'Penelope', age: 39 }
];
let query =
employees
.as_queryable()
.where(i=>i.age >= 35)
.select(i => ({name: i.name, age: i.age + 100}))
;
console.log(query.to_array());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment