Created
November 10, 2019 15:55
-
-
Save XoseLluis/69ab06d98dad132a36ee1c580e08df1f to your computer and use it in GitHub Desktop.
Just a POC of how to add deferred-lazy methods to an Iterable. As I've said this is just a POC, for something real go and use lazy.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ExtendedIterable{ | |
constructor(iterable){ | |
this.iterable = iterable; | |
} | |
*[Symbol.iterator](){ | |
for (let it of this.iterable){ | |
yield it; | |
} | |
} | |
map(fn){ | |
//I need to use the old "self" trick, cause we can not declare a generator with an arrow function | |
//so as we are using a normal function, "this" is dynamic, so we have to trap it via "self" | |
let self = this; | |
function* _map(fn){ | |
for (let it of self.iterable){ | |
yield fn(it); | |
} | |
}; | |
let newIterable = _map(fn); | |
return new ExtendedIterable(newIterable); | |
} | |
filter(fn){ | |
let self = this; | |
function* _filter(fn){ | |
for (let it of self.iterable){ | |
if (fn(it)) | |
yield it; | |
} | |
}; | |
let newIterable = _filter(fn); | |
return new ExtendedIterable(newIterable); | |
} | |
} | |
function* citiesGeneratorFn(){ | |
let cities = ["Xixon", "Toulouse", "Lisbon", "Tours"]; | |
for (city of cities){ | |
yield city; | |
} | |
} | |
let cities = citiesGeneratorFn(); | |
//I could just use the array, and array is iterable and the citiesGenerator is not doing any processing, just retrieving the value directly | |
//let cities = ["Xixon", "Toulouse", "Lisbon", "Tours"]; | |
let extendedIterable = new ExtendedIterable(cities); | |
let result = extendedIterable.map(it => it.toUpperCase()) | |
.filter(it => it.startsWith("T")); | |
for (let it of result){ | |
console.log(it); | |
} | |
//or just convert to array and join it | |
//console.log([...result].join(";")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment