Skip to content

Instantly share code, notes, and snippets.

@Comandeer
Last active January 17, 2020 22:52
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 Comandeer/e5a6fc4e91a267ea4af2ec64563ce57c to your computer and use it in GitHub Desktop.
Save Comandeer/e5a6fc4e91a267ea4af2ec64563ce57c to your computer and use it in GitHub Desktop.
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 );
@Bigismall
Copy link

console.log(0, array[0]); returns "undefined" instead of 1

@Comandeer
Copy link
Author

Thx, I've fixed the code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment