Advertisement
cherkashin-metacpa

Iterator exmp

Apr 22nd, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Matrix {
  2.   constructor (width, height, element = (x, y) => undefined) {
  3.     this.width = width;
  4.     this.height = height;
  5.     this.content = [];
  6.    
  7.     for (let y = 0; y < height; y++) {
  8.       for (let x = 0; x < width; x++) {
  9.         this.content[y * width + x] = element(x, y);
  10.       }
  11.     }
  12.   }
  13.  
  14.   get (x, y) {
  15.     return this.content[y * this.width + x];
  16.   }
  17.  
  18.   set (x, y, value) {
  19.     this.content[y * this.width + x] = value;
  20.   }
  21.  
  22.   [Symbol.iterator] = function () {
  23.     return new MatrixIterator(this);
  24.   }
  25. }
  26.  
  27. class MatrixIterator {
  28.   constructor (matrix) {
  29.     this.x = 0;
  30.     this.y = 0;
  31.     this.matrix = matrix;
  32.   }
  33.  
  34.   next () {
  35.     if (this.y === this.matrix.height) {
  36.       return {
  37.         done: true
  38.       }
  39.     }
  40.    
  41.     let value = {
  42.       x: this.x,
  43.       y: this.y,
  44.       value: this.matrix.get(this.x, this.y)
  45.     };
  46.    
  47.     this.x++;
  48.    
  49.     if (this.x === this.matrix.width) {
  50.       this.x = 0;
  51.       this.y++;
  52.     }
  53.    
  54.     return {
  55.       value,
  56.       done: false
  57.     };
  58.   }
  59. }
  60.  
  61. let matrix = new Matrix(3, 3, (x, y) => null);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement