// Wrap an array of 5 elements. var array = wrapArray([0, 1, 2, 3, 4]) ... // Outputs: 3 console.log(array[-1]);
Nope: it would return 4. :)
Speaking of which, it also seems that "-0"
would be parsed to array.length - 0 == array.length
, giving us undefined
... So I guess the lack of forEach etc is not even the main problem of this naive implementation. :)
Other than that, a very interesting article!
The naive implementation defines a property for "-0"
, but it can only be accessed by explicitly using that string as a property name. Negative zero is a distinct value from zero in JavaScript, but both are coerced to strings as "0"
. I thought about adding an if (i === 0) { return; }
in there, but I figured that most people wouldn't think twice about it :-).
This is a nice write up. I had the same idea a while back and wrote this function:
function sliceArray(array=[]) { return new Proxy(array, { get(target, key) { const sliceMatch = key.match(/^(-?\d+)?:(-?\d+)?$/); if(sliceMatch) { const [/* match */, startIndex=0, endIndex=target.length ] = sliceMatch; return sliceArray(target.slice(+startIndex, +endIndex)); } return target[key]; } }); } const a = sliceArray([1,2,3,4,5,6,7,8,9,10]); console.log(a['3:-2']['1:']); // outputs: [5, 6, 7, 8]
I opted to use the native Array.prototype.slice
since it handles negative indexes (I didn't think to add a step
input, but it's not supported by slice
anyway).
I’m not exactly sure how good it would be, but there are likely things you could exchange with PyBee’s Batavia project, which implements Python on top of JavaScript. They already have Python lists and slices sort out. They would love any help to correct the implementation if you find any problems as well!