Last active
October 18, 2022 04:36
-
-
Save semlinker/fb87ed33c57ccdf4da0a4117ec311c2a to your computer and use it in GitHub Desktop.
Proxy API usage scenarios —— Enhanced Array
This file contains 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
function enhancedArray(arr) { | |
return new Proxy(arr, { | |
get(target, property, receiver) { | |
const range = getRange(property); | |
const indices = range ? range : getIndices(property); | |
const values = indices.map((index) => { | |
const key = index < 0 ? target.length + index : index; | |
return Reflect.get(target, key, receiver); | |
}); | |
return values.length === 1 ? values[0] : values; | |
}, | |
}); | |
function getRange(str) { | |
var [start, end] = str.split(":").map(Number); | |
if (typeof end === "undefined") return false; | |
let range = []; | |
for (let i = start; i < end; i++) { | |
range = range.concat(i); | |
} | |
return range; | |
} | |
function getIndices(str) { | |
return str.split(",").map(Number); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment