Skip to content

Instantly share code, notes, and snippets.

@ericyd
Last active October 25, 2019 04:52
Show Gist options
  • Save ericyd/b342e6bc28200eab1e304481bdbc17d5 to your computer and use it in GitHub Desktop.
Save ericyd/b342e6bc28200eab1e304481bdbc17d5 to your computer and use it in GitHub Desktop.
Two dimensional array in JS
/*
It is common to address two-dimensional array problems with nested arrays.
It works, but then you have all these nasty references like array[0][3].
This class abstracts the element selection to a method which takes the x and y indices
as arguments.
If you wanted to go purely functional obviously you can, but this class demonstrates the idea.
*/
class TwoDimensionalArray {
constructor(array, xDim) {
if (array.length % xDim !== 0) {
throw new Error(`Your array is not rectangular! Length: ${array.length}, x-dimension: ${xDim}`)
}
this.array = array
this.xDim = xDim
}
index(x, y) {
return this.array[(y * this.xDim) + x]
}
}
const incrementalArray = size => new Array(size).fill(0).map((_, i) => i)
const xDim = 4
const yDim = 3
const twoDArr = new TwoDimensionalArray(incrementalArray(xDim * yDim), xDim)
// access elements in our array
const xs = incrementalArray(xDim)
const ys = incrementalArray(yDim)
ys.forEach(y => {
xs.forEach(x => {
console.log(`x: ${x}, y: ${y}, res: ${twoDArr.index(x, y)}`)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment