Skip to content

Instantly share code, notes, and snippets.

@Comandeer
Last active Jan 17, 2020
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@Bigismall Bigismall commented Sep 16, 2019

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

@Comandeer

This comment has been minimized.

Copy link
Owner Author

@Comandeer Comandeer commented Sep 17, 2019

Thx, I've fixed the code.

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