-
-
Save Comandeer/e5a6fc4e91a267ea4af2ec64563ce57c to your computer and use it in GitHub Desktop.
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
class NegativeArray extends Array { | |
constructor( ...args ) { | |
super( ...args ); | |
return new Proxy( this, { | |
get( target, property, ...args ) { | |
const translatedProperty = translateProperty( target, property ); | |
return Reflect.get( target, translatedProperty, ...args ); | |
}, | |
set( target, property, value, ...args ) { | |
const translatedProperty = translateProperty( target, property ); | |
return Reflect.set( target, translatedProperty, value, ...args ); | |
} | |
} ); | |
} | |
} | |
function translateProperty( target, property ) { | |
const propertyAsNumber = Number( property ); | |
if ( Number.isNaN( propertyAsNumber ) || propertyAsNumber >= 0 ) { | |
return property; | |
} | |
const translatedProperty = target.length - Math.abs( propertyAsNumber ); | |
if ( translatedProperty < 0 ) { | |
throw new RangeError( 'Array index out of range' ); | |
} | |
return translatedProperty; | |
} | |
const array = new NegativeArray( 1, 2, 3, 4 ); | |
console.log( array[ -1 ] ); | |
array[ -2 ] = 6; | |
console.log( array ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
console.log(0, array[0]);
returns "undefined" instead of1