Master de II. ULL. 1er cuatrimestre
Read the chapter Generators of JavaScript.info reproducing the examples and exercises. Submit a report.
Surely you are going to have a look at the chapter Iterables. You can add the examples and exercises of the Iterables chapter at the beginning of the report.
Group
class from the previous exercise iterableWrite the solution as an ES6 module so that can be imported with this syntax:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/env node
import { Group } from './eloquent-js-6-2-group-with-generators.js';
let group = Group.from([10, 20]);
console.log(group.has(10));
// → true
console.log(group.has(30));
// → false
group.add(10);
group.delete(10);
console.log(group.has(10));
// → false
for (let value of Group.from(['a', 'b', 'c'])) {
console.log(value);
}
// → a
// → b
// → c
See the Node.js doc Modules: Packages for more details on the use of ECMA 6 Modules in Node.js.
Here is a template for the class Group
:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Group {
constructor() {
// ... your code
}
add(elt) {
// ... your code
}
delete(elt) {
// ... your code
}
has(elt) {
// ... your code
}
static from(iterable) {
// Takes an iterable object as argument and
// creates a group that contains all the values
// produced by iterating over it.
}
*[Symbol.iterator] () {
// ... Your code
}
}
export { Group };
Simplify the solution to making the Group
class iterable using a generator instead of a plain iterator as suggested in Chapter 11 of the book Eloquent JS
Writing iterators is often much easier when you use generator functions. The iterator for the Group class can be written with this generator:
1
2
3
4
5
Group.prototype[Symbol.iterator] = function*() {
for (let i = 0; i < this.members.length; i++) {
yield this.members[i];
}
};