Representation of 2d space of indefinite size with JS arrays - negative indices?

I would like to represent 2d Cartesian coordinates in a 2d JS array. The 2d space has an indefinite size (can also extend to -x and -y space). This is good for positive values ​​of x and y, but with a minimum index of 0 in JS arrays, I cannot go into negative spaces x and y.

I read a little information about the possibility of using negative indices in JS and that, apparently, it is technically possible, although not supported properly (for example, the functions of the moght array do not work properly).

I'm sure others must have had a similar requirement, so I would like to ask - what is the recommended way to model this in JS? Are negative array indexes a workable solution?

+3
javascript
Apr 12 2018-12-12T00:
source share
1 answer

Are you sure you need negative indices? Typically, each coordinate system for computer graphics starts with (0/0) in the upper left corner of the screen. And they draw their axes somewhere else.

So, the solution for the final size simply converts the coordinates. You can also use negative indexes for arrays, but better call it "keys on array objects." If you know their limitations, you can use them:

  • Array.length only works for positive indices.
  • Therefore, you cannot loop from 0 to a.length - you will need to find another solution. (and don’t think about what you need).
  • So, you need to determine a negative start for the loop - let it be a constant or even another property of your array object (without the automatic update function!).

But you say that your space is indefinite. The problem is that there is no internal data structure - in no programming language. Of course, massive indexes can become very large, but do you really need them? I am very sure that a two-dimensional array of size (2 ^ 32) ^ 2 is nothing but a huge waste of memory space - or at least something that makes your application extremely slow.

It is better to think of a one-dimensional array with objects representing points. You can easily iterate over it, you can have any number for coordinate values, and they don’t need so much memory.

+1
Apr 12 2018-12-12T00:
source share



All Articles