forked from davidflanagan/jstdg7
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilter.js
More file actions
19 lines (18 loc) · 663 Bytes
/
filter.js
File metadata and controls
19 lines (18 loc) · 663 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Return an iterable object that filters the specified iterable,
// iterating only those elements for which the predicate returns true
function filter(iterable, predicate) {
let iterator = iterable[Symbol.iterator]();
return { // This object is both iterator and iterable
[Symbol.iterator]() { return this; },
next() {
for(;;) {
let v = iterator.next();
if (v.done || predicate(v.value)) {
return v;
}
}
}
};
}
// Filter a range so we're left with only even numbers
[...filter(new Range(1,10), x => x % 2 === 0)] // => [2,4,6,8,10]