Sistemas y Tecnologías Web: Servidor

Master de II. ULL. 1er cuatrimestre


Organization ULL-MII-SYTWS-2122   Classroom ULL-MII-SYTWS-2122   Campus Virtual SYTWS   Chat Chat   Profesor Casiano

Generators in JS

Description

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.

Exercise Groups in the book EloquentJS Chapter 6

  1. Study and solve the exercise Groups in the book EloquentJS Chapter 6
  2. Study an solve the Iterable groups extension of the exercise Groups in EloquentJS Chapter 6 making the Group class from the previous exercise iterable
  3. Write 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.

  4. 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 };
    
  5. 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];
         }
     };
    

See

Comment with GitHub Utterances