Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

361
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda