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

111
Views
Nested functions not affecting objects in bidimensional array declared within global scope

I have a bidimensional array filled with Cell objects.

How can I do to make addToGrid(asset); (and nested functions) use the context of each Cell to set cells so that I can use it in draw method ?

class Cell {
  constructor(value) {
     this.value = value;
  }
  
  makeAlive = () => {
    this.value |= (1 << 0)
  }

  incrementNeighbours = (num) => {
    this.value += 2;
  }
}

// Main
let cols;
let rows;
let cells;
let resolution = 2;
let infos = {};

s.setup = async () => {
  cols = 256;
  rows = 256;
  s.createCanvas(cols * resolution, rows * resolution);
  s.frameRate(60);

  cells = [...Array(cols)].map(x => Array(rows).fill(new Cell(0)));
  const loader = new AssetLoader();
  const asset= await loader.loadAsync('type', 'name');

  addToGrid(asset);
}

s.draw = () => {
    .
    .
    .
    // cells is not affected by addToGrid

}

const addToGrid = (asset) => {
  for (let i = 0; i < asset.length; i++) {
    .
    .
    .
    addStrToGrid(col, row, asset[i]);
  }
}

const addStrToGrid = (col, row, str) => {
  for (const c of str) {
      becomeAlive(col, row);
  }
}

const becomeAlive = (x, y) => {
  cells[x - 1][y - 1].incrementNeighbours();
  cells[x - 1][y].incrementNeighbours();
  cells[x - 1][y + 1].incrementNeighbours();
  cells[x][y - 1].incrementNeighbours();
  cells[x][y].makeAlive();
  cells[x][y + 1].incrementNeighbours();
  cells[x + 1][y - 1].incrementNeighbours();
  cells[x + 1][y].incrementNeighbours();
  cells[x + 1][y + 1].incrementNeighbours();
}

s.setup & s.draw are from the library p5.js which are triggered respectively !

about 4 years ago · Juan Pablo Isaza
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!