is there any better way to improve this if/else? (multiple times &&, !==, ===)

Viewed 28

basically I have this if/else

and it has &&, !==, same variables repeated a lot of times

so maybe is there a better way to do so

if (x !== prevCoords.x && y === prevCoords.y) {
  return "moving on X axis";
} else if (y !== prevCoords.y && x === prevCoords.x) {
  return "moving on Y axis";
} else if (y !== prevCoords.y && x !== prevCoords.x) {
  return "rotated so X/Y together move";
} else {
  return "don't move"
}

the array is a series of points with x and y

like this:

let array = [{
    x: 10
    y: 20
  },
  {
    x: 15
    y: 20
  },
  {
    x: 25,
    y: 9
  },
  {
    x: 25,
    y: 30
  },
  {
    x: 25,
    y: 25
  },
  {
    x: 25
    y: 25
  }
]

array.forEach((thisCoords, index) => {
  let prevCoords = array[index - 1] ? array[index - 1] : array[index]
})


what I tried?

function activeAxis() {
  const isOnlyX = x !== prevCoords.x && y === prevCoords.y;
  const isOnlyY = y !== prevCoords.y && x == prevCoords.x;
  const isRotated = y !== prevCoords.y && x !== prevCoords.x;

  if (isOnlyX) return "x";
  if (isOnlyY) return "y";
  if (isRotated) return "rotated";
  return "don't move";
}

but I don't know is there is a better way. to make it more readable and easy to maintain.

thanks

0 Answers
Related