在过去的几天里,我花了很多时间才使我的代码正常工作,但我无法使其正常工作!!
我想要完成的是使用es6代理链接生成器函数,如下所示。似乎我可以将这些列表操作函数添加到生成器原型中,但我想使用代理代替我的学习目的。
rangeGenerator
.map('project function here')
.filter('predicate function here')
.forEach('do some last work');
有谁可以请看下面我的代码并告诉我我做错了什么以及如何解决这个问题,好吗?
谢谢!
function range(end) {
return function* rangeGf() {
for (let i = 1; i <= end; i++) {
yield i;
}
}
}
const makeHandler = (options) => {
const handler = {
get: function(target, property, resolver) {
if (property === 'map') {
return map.bind(target);
}
if (property === 'filter') {
return filter.bind(target);
}
}
};
function map(project) {
console.log('project', project);
const newTarget = this;
function* mapGf() {
for (let v of newTarget()) {
yield v * 2; //hard coding for now...
}
}
// return generator object wrapped by proxy
return new Proxy(mapGf(), handler);
}
function filter(predicate) {
console.log('predicate', predicate);
const newTarget = this;
function* filterGf() {
for (let v of newTarget) {
if(v % 3 === 0) { //hard coding for now...
yield v;
}
}
}
// return generator object wrapped by proxy
return new Proxy(filterGf(), handler);
}
return handler;
};
const rangeGf = range(10);
const $range = new Proxy(rangeGf, makeHandler())
// for now, I'm trying to make this simple one work!
for (var i of $range.map('project')) {
console.log(i)
}
for (var i of $range.map('project')) {
console.log(i)
}