Can anyone give me a direction on how to implement python like syntax of lists array[-1] using Babel in javascript? I mean how to implement negative indexes.
Asked
Active
Viewed 63 times
-2
-
You can use slice for that `array.slice(-1)` – ptothep Jan 05 '21 at 17:18
-
I know, but I am interesting in how to implement this as a new syntactic sugar using babel – FoxyJS Jan 05 '21 at 17:21
-
That would be difficult to do with Babel - you could look for indexing with a negative value and try replacing that with the slice @ptothep suggests, but what if it turns out that wasn't an *array* being indexed into? There's no type information to leverage. Besides that a tutorial on writing a new Babel transform would be too broad for an SO question. – jonrsharpe Jan 05 '21 at 17:22
-
Does this answer your question? [Python to JavaScript converter](https://stackoverflow.com/questions/22595989/python-to-javascript-converter) – Washington Guedes Jan 05 '21 at 17:28
1 Answers
0
You could go with your own proxy implementation and then use it.
const letters = ['a', 'b', 'c', 'd', 'e'];
const proxy = new Proxy(letters, {
get(target, prop) {
if (!isNaN(prop)) {
prop = parseInt(prop, 10);
if (prop < 0) {
prop += target.length;
}
}
return target[prop];
}
});
proxy[0]; // => 'a'
proxy[-1]; // => 'e'
proxy[-2]; // => 'd'
Please refer to this article on medium explaining in detail how to do this. I do not know of another way, perhaps there is a babel plugin that could help.

Julian Kleine
- 1,539
- 6
- 14