Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

359
Vistas
Polymorphism in node.js

I have a 2D matrix with 0s and 1s - respectively representing Water and Land. It is used to generate an animated gif with Perlin noise (moving water and waves clashing on shores...).

However I wish to refactor my code and use polymorphism in the following manner:

For each element in my matrix, based on the value, I wish to create a new WaterTile or LandTile (which will represent a 30x30 set of pixels that are either a mixture of blue for water, and some combinations of green/yellow/blue for land).

WaterTile and LandTile will be inherited from BaseTile (this is an abstract class), having just 2 vars (x, y for coordinates) and a draw() method (this method for the BaseTile class does nothing, its just there if it has to be defined).

Child classes will be overriding the draw() method.

Map will be a 2D array that whose elements will be WaterTiles and LandTiles.

After that, in my main method, I will have this (pseudocode for simplicity, i is index of row, j is index of element in that row):

foreach (row in matrix) {
     foreach (element in row) {
          if (matrix[i][j] == 0) map[i][j] == new WaterTile();
          else map[i][j] == new LandTile();
      }
 }

After this I will need to invoke more methods for the LandTiles, and then have a new foreach loop, simply having

map[i][j].draw();//invoking draw method based on type

I know this can be done in other ways, but i wish to avoid having if statements that check for the type and call the draw method based on the type, and also practice clean code and learn something new.

If someone can provide me a simple example, ive looked at some already but havent found what I want.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Put the different actions inside the if statement you already have.

Or, just call the draw method, and let each instance do what it is does with draw.

Or encapsulate the if inside a function and use that.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda