in svelte using getter with Object.values() "Maximum call stack size exceeded"

Viewed 38

I am using the svelte.js framework

enter image description here

and I am using a function that returns an object like this {x, y, rotated, isMoving}

the problem is that isMoving use getter

{
  get isMoving() {
    return Object.values(this)
  }
}

basically I want all the values to be in a array and then loop on it.


function activeAxis() {
  return {
    x: x !== prevCoords.x && y === prevCoords.y,
    y: y !== prevCoords.y && x === prevCoords.x,
    rotated: y !== prevCoords.y && x !== prevCoords.x,
    get isMoving() {
      return Object.values(this)
    }
  };
}


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
  }
]

2 Answers
  1. It's not related to svelte
  2. By calling Object.values(this) in a getter you are calling this getter in a loop and never return an actual value.
  3. Just don't do this

Better use one of these:

function activeAxis() {
  return {
    x: x !== prevCoords.x && y === prevCoords.y,
    y: y !== prevCoords.y && x === prevCoords.x,
    rotated: y !== prevCoords.y && x !== prevCoords.x,
  };
}

console.log(Object.values(activeAxis())
function activeAxis() {
  return {
    x: x !== prevCoords.x && y === prevCoords.y,
    y: y !== prevCoords.y && x === prevCoords.x,
    rotated: y !== prevCoords.y && x !== prevCoords.x,
    isMoving() {
      return Object.values(this)
    }
  };
}

console.log(activeAxis().isMoving())

like he said to you @konrad, if you can try to not use this
and I saw that you answered @H.B. with the purpose of the getter function.

so with these details, I think that
the best way is to refactor your code
and not use this and also not a for loop because isn't necessary

function activeAxis() {
  const sameX = x === prevCoords.x;
  const sameY = y === prevCoords.y;

  return {
    x: sameY && !sameX,
    y: sameX && !sameY,
    rotated: !sameX && !sameY,
    sameCoord: sameX && sameY
  };
}

Related