Last active
February 1, 2020 23:21
-
-
Save spence/a5003c56c88916f861c88e1a272e6aba to your computer and use it in GitHub Desktop.
Messing around with multidimensional arrays in JS.
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 createMultidimensionalArray = (dimensions, defaultValue = undefined) => { | |
if (dimensions < 1) { | |
throw new Error('Dimensions must be greater than 0'); | |
} | |
return new Proxy([], { | |
get(target, prop) { | |
if (!(prop in target)) { | |
if (dimensions === 1) { | |
return defaultValue; | |
} | |
target[prop] = createMultidimensionalArray(dimensions - 1, defaultValue); | |
} | |
return target[prop]; | |
}, | |
set(target, prop, value) { | |
if (dimensions === 1) { | |
target[prop] = value; | |
} | |
// no-op | |
}, | |
}); | |
}; | |
// Regular array | |
const regArray = createMultidimensionalArray(1); | |
regArray[1] === undefined; | |
regArray[1] = 1000; | |
regArray[1] === 1000; | |
// 5-dimension array with default value of 0 | |
const fiveArray = createMultidimensionalArray(5, 0); | |
fiveArray[1][2][3][4][5] === 0; | |
fiveArray[1][2][3][4][5] = 10; | |
fiveArray[1][2][3][4][5] === 10; | |
delete fiveArray[1][2][3][4][5]; | |
fiveArray[1][2][3][4][5] === 0; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment