Skip to content

Instantly share code, notes, and snippets.

@ddprrt
Created February 22, 2022 09:32
Show Gist options
  • Save ddprrt/674aee32858cb933ed1ab11fa8ca2830 to your computer and use it in GitHub Desktop.
Save ddprrt/674aee32858cb933ed1ab11fa8ca2830 to your computer and use it in GitHub Desktop.
A lazy evaluated collection class
class Collection {
coll;
constructor(coll) {
this.coll = coll;
}
map(fn) {
return new MapCollection(this, fn);
}
filter(fn) {
return new FilterCollection(this, fn);
}
collect(n) {
return [...new Collector(this, n)];
}
*[Symbol.iterator]() {
for (let o of this.coll) {
yield o;
}
}
}
class Collector {
coll;
limit;
constructor(coll, limit = Number.MAX_VALUE) {
this.coll = coll;
this.limit = limit;
}
*[Symbol.iterator]() {
let iter = this.coll[Symbol.iterator]();
let result = iter.next();
let count = 0;
while (!result.done && count < this.limit) {
yield result.value;
count++;
result = iter.next();
}
}
}
class MapCollection extends Collection {
fn;
constructor(coll, fn) {
super(coll);
this.fn = fn;
}
*[Symbol.iterator]() {
for (let o of this.coll) {
yield this.fn(o);
}
}
}
class FilterCollection extends Collection {
fn;
constructor(coll, fn) {
super(coll);
this.fn = fn;
}
*[Symbol.iterator]() {
for (let o of this.coll) {
if (this.fn(o)) {
yield o;
}
}
}
}
class Fibonacci {
i = 0;
j = 1;
constructor() {}
*[Symbol.iterator]() {
do {
let next = this.i + this.j;
yield this.j;
this.i = this.j;
this.j = next;
} while (this.j + this.i < Number.MAX_VALUE);
}
}
//const set = new Set([1, 2, 2, 3, 4, 5, 6, 0, 4, 2, 3, 0]);
//console.log(...set);
//const coll = new Collection(set).filter((i) => i % 2 === 0).map((el) => el * 2);
//console.log(coll.collect(2));
const times_two = (x) => x * 2;
const is_even = (x) => x % 2 === 0;
const fib = new Collection(new Fibonacci());
for (let o of fib.filter(is_even).map(times_two).collect(5)) {
console.log(o);
}
function* fibonacci() {
let i = 0;
let j = 1;
do {
let next = i + j;
yield j;
i = j;
j = next;
} while (j + i < Number.MAX_VALUE);
}
function* produce_numbers(start = 0, max = Number.MAX_VALUE) {
let i = start;
while (i < max) {
yield i++;
}
}
console.log(new Collection(produce_numbers()).collect(10));
console.log(new Collection(fibonacci()).filter(is_even).collect(5));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment