mardi 12 avril 2016

Array.from pour initialiser un tableau

Array.from permet d'initialiser un tableau.

 Array.from(new Array(5), (x,i) => i)    [ 0, 1, 2, 3, 4 ]

Voici la nouvelle écriture de la classe Grille.

'use strict';
class Vector {

  constructor (x, y){
    this.x = x;
    this.y = y;
  }
}


class Grid {

  constructor (W, H){
    this.width = W;
    this.height = H;

    this.space = Array.from(new Array(this.height), () => new Array(this.width));

  }

  get ( vector) {
    return this.space[vector.x][vector.y];
  }

  set ( vector, value){
    this.space[vector.x][vector.y] = value;
  }
}

// test

let G = new Grid (5,5);
console.log(G.space.length);
G.set( new Vector(2,2),"genial");
console.log(G.get( new Vector(2,2)));

Aucun commentaire:

Enregistrer un commentaire