Skip to content

Instantly share code, notes, and snippets.

@redstar504
Last active September 15, 2020 23:21
Show Gist options
  • Save redstar504/f13cc12bf8fc4491fa1594beb22e6613 to your computer and use it in GitHub Desktop.
Save redstar504/f13cc12bf8fc4491fa1594beb22e6613 to your computer and use it in GitHub Desktop.
Proxy matrix with setter
const [width, height] = [10,10] // 10x10 matrix
const element = (index) => index;
const array = Array.from({length: width * height}, (_,index) => index);
const handler = {
get: (array, rowIndex) => {
return new Proxy(array.slice(width * +rowIndex, width * (+rowIndex + 1)), Object.assign({array, rowIndex, width}, handler));
},
set: function(target, property, value, receiver) {
let key = this.rowIndex * width + Number(property);
this.array[key] = value;
}
}
const matrix = new Proxy(array, handler);
matrix[3][5] = 3000;
console.log(matrix); // index at 35 is 3000, setter worked...
console.log(matrix[3][5]); // but accessing through the proxy getter still returns 35? :\
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment