Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

358
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!