Last active
September 16, 2020 16:21
-
-
Save stenno/3a352de0359ecbef64a0f8046644a6ac to your computer and use it in GitHub Desktop.
matrix behavior on array with Proxy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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