class Lazy {
count = 0;
constructor(iterable) {
this.callback = (next) => {
for (const item of iterable) {
if (this.count === 0) {
break;
} else {
next(item);
}
}
};
}
map(fn) {
const prev = this.callback;
this.callback = (next) => {
prev((item) => {
next(fn(item));
});
};
return this;
}
filter(fn) {
const prev = this.callback;
this.callback = (next) => {
prev((item) => {
if (fn(item)) {
next(item);
}
});
};
return this;
}
take(n) {
this.count = n;
const result = [];
this.callback((item) => {
this.count--;
result.push(item);
});
return result;
}
}
const value = new Lazy([0.5, 1, 2, 3, 4, 5, 6, 7]).map(x => x * 2).filter(x => x % 2 === 0).take(3);
console.log(value);
js实现lazy惰性求值
于 2022-09-01 16:43:44 首次发布