Home > Net >  How to check values of adjacent items in a list? Javascript
How to check values of adjacent items in a list? Javascript

Time:12-15

I have a list of list that looks something like this

let pixels = [
 [0,0,0,0]
 [0,0,0,0]
 [0,0,0,0]
]

and I would like to iterate through this list and create a list of the adjacent items for each item. In this example the output I would want from pixels[0][0] is: [undefined, undefined, undefined, undefined, 0, undefined, 0, 0]. But when I run my code I get I get an error

The code cannot read pixels[-1][-1], I just want it to read it as undefined and not crash the whole program.

let pixels = [
  [0, 0, 0, 0],
  [0, 0, 0, 0],
  [0, 0, 0, 0]
]

function adjacent(i1, i2) {
  const yep = [pixels[i1 - 1][i2 - 1], pixels[i1 - 1][i2], pixels[i1 - 1][i2   1], pixels[i1][i2 - 1], pixels[i1][i2   1], pixels[i1   1][i2 - 1], pixels[i1   1][i2], pixels[i1   1][i2   1]]
  return yep
}

console.log(adjacent(1,4))

console.log(adjacent(-1,-1))

CodePudding user response:

When i is out of range, pixel[i] is undefined, and undefined[anything] is an error.

You can use optional chaining to suppress these errors.

let pixels = [
  [0, 0, 0, 0],
  [0, 0, 0, 0],
  [0, 0, 0, 0]
]

function adjacent(i1, i2) {
  const yep = [pixels[i1 - 1]?.[i2 - 1], pixels[i1 - 1]?.[i2], pixels[i1 - 1]?.[i2   1], 
    pixels[i1]?.[i2 - 1], pixels[i1]?.[i2   1], pixels[i1   1]?.[i2 - 1], 
    pixels[i1   1]?.[i2], pixels[i1   1]?.[i2   1]
  ]
  return yep
}

console.log(adjacent(1, 4))

console.log(adjacent(-1, -1))

CodePudding user response:

You can use && to test the first element exists

let pixels = [
  [0, 0, 0, 0],
  [0, 0, 0, 0],
  [0, 0, 0, 0]
]

function adjacent(i1, i2) {
  const yep = [
  pixels[i1 - 1] && pixels[i1 - 1][i2 - 1], 
  pixels[i1 - 1] && pixels[i1 - 1][i2], 
  pixels[i1 - 1] && pixels[i1 - 1][i2   1], 
  pixels[i1]     && pixels[i1][i2 - 1], 
  pixels[i1]     && pixels[i1][i2   1], 
  pixels[i1   1] && pixels[i1   1][i2 - 1], 
  pixels[i1   1] && pixels[i1   1][i2],
  pixels[i1   1] && pixels[i1   1][i2   1]]
  return yep
}

console.log(adjacent(1,4))

console.log(adjacent(-1,-1))

CodePudding user response:

In addition to using optional chaining, you can use two loops to generate the adjacent coordinates rather than manually writing out each possibility, which is easier to maintain.

let pixels = [
  [0, 0, 0, 0],
  [0, 0, 0, 0],
  [0, 0, 0, 0]
]

function adjacent(i1, i2) {
  const res = [];
  for(let deltaY = -1; deltaY <= 1; deltaY  )
    for(let deltaX = -1; deltaX <= 1; deltaX  )
      if(deltaY != 0 || deltaX != 0)
        res.push(pixels[i1   deltaY]?.[i2   deltaX]);
  return res;
}

console.log(...adjacent(1,4))

console.log(...adjacent(-1,-1))

  • Related