Skip to content

Instantly share code, notes, and snippets.

@stenno
Last active September 16, 2020 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stenno/3a352de0359ecbef64a0f8046644a6ac to your computer and use it in GitHub Desktop.
Save stenno/3a352de0359ecbef64a0f8046644a6ac to your computer and use it in GitHub Desktop.
matrix behavior on array with Proxy
const [width, height] = [10,10] // 10x10 matrix
const element = (index) => index;
// lets create the flat array first
const array = Array.from({length: width * height}, (_,index) => element(index));
// lets create the proxy handler
// we return the 'row' of the index by filtering the respective elements
const handler = {
get: (array, rowIndex) => array.slice(+rowIndex * width, (+rowIndex + 1) * width)
};
const matrix = new Proxy(array, handler);
const topRow = matrix[0]; // the get handler will be called with (array, "0")
// as matrix[i] now returns the row array, we can now access the array as if it was multidimensional
// topRow should now be [0,1,2,3,4,5,6,7,8,9]
console.log(matrix[3][5]);
// should output 35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment