我想链接这些方法调用:
utils.map([1,2,3,4,5], function (el) { return ++el; } )和
utils.filter(function (el) {return !el%2; }它们各自都工作得很好,但以下各项不能正常工作。我怎样才能让下面的代码工作呢?
utils
.map([1,2,3,4,5], function (el) { return ++el; })
.filter(function (el) { return !el%2; }下面是我的utils对象:
var utils = {
each: function (collection, iteratee){
return collection.forEach(iteratee);
},
map: function (collection, iteratee) {
return collection.map(iteratee);
},
filter: function (collection, predicate) {
return collection.filter(predicate);
},
find: function (collection, predicate) {
return collection.find(predicate);
}
}我知道当我链接两个方法时,参数会发生变化,我只需要提供iteratee而不是一个集合。如何做到这一点?
提前谢谢。如果需要,我愿意解释一个特定的概念。
发布于 2021-01-14 08:24:51
这是带有ES6类设计的trincot响应的更新版本。
class Collection {
constructor(collection) {
if (collection == null || !Array.isArray(collection)) {
throw new Error('collection is null or not an array');
}
this.collection = collection;
}
each(iteratee) {
this.collection.forEach.call(this.collection, iteratee);
return this;
}
map(iteratee) {
return new Collection(this.collection.map.call(this.collection, iteratee));
}
filter(predicate) {
return new Collection(this.collection.filter.call(this.collection, predicate));
}
find(predicate) {
return this.collection.find.call(this.collection, predicate);
}
contains(value) {
return this.collection.includes.call(this.collection, value);
}
get() {
return this.collection;
}
}
const result = new Collection([1, 2, 3, 4, 5])
.map(el => ++el)
.filter(el => !(el % 2))
.get();
console.log(result);
console.log(new Collection([1, 2, 3, 4, 5]).find(e => e === 2));
console.log(new Collection([1, 2, 3, 4, 5]).contains(2));.as-console-wrapper { top: 0; max-height: 100% !important; }
https://stackoverflow.com/questions/35888688
复制相似问题