Skip to content

Instantly share code, notes, and snippets.

@krismuniz
Last active September 1, 2021 23:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krismuniz/32247824fb7efe47faa5047d8a4b9f28 to your computer and use it in GitHub Desktop.
Save krismuniz/32247824fb7efe47faa5047d8a4b9f28 to your computer and use it in GitHub Desktop.
How to add back-access syntax to JS Arrays and strings

This allows you to use back-access syntax to access items in an array or characters in a string.

In practical terms, it adds the negative integer in arr[-1] to the length of the array/string and tries to search for that property inside the object.

Examples

const arr = backAccess(['first', 'second', 'last'])
arr[-1] // => "last"
arr[-2] // => "second"
arr[-3] // => "first"

const str = backAccess('Hello world!')
str[-1] // => "!"
str[-2] // => "d"
str[-3] // => "l"

Conclusion

Proxies are awesome! But maybe a bit useless in practical terms xD

module.exports = function backAccess (arg) {
return new Proxy(typeof arg === 'string' ? new String(arg) : arg, {
get: (obj, prop, receiver) => {
try {
let key = parseInt(prop)
return Reflect.get(obj, key < 0 ? obj.length + key : key, receiver)
} catch (e) {
return Reflect.get(obj, prop, receiver)
}
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment