Built-in-like Range in JavaScript
Make it possible to generate any range of integers with built-in-like syntax.
Motivation? Honestly, none. Zero. Except for fun & study.
Basic functionality
You start by overriding the prototype of Number
with itself, but proxed.
In this way, any normal operations related to the prototype are not lost.
In the proxy you listen for access to any property via a getter. The third argument (receiver
) is the "object", in this case the number itself - you call it start
. It's already the right type, number.
The second argument corresponds to the name of the property, its typeof
is indeed string
.
It is sufficient to use parseInt
and, if it still isNaN
just throw an error/warning. Or just ignore it silently and fallback by returning start
.
Assured that the typeof end
is also number
, you can proceed to generate the range.
Basic functionality is complete. Now the following code is perfectly valid.
To make it not-end-inclusive, use
Array(end - start)
instead ofArray(end - start + 1)
.
Reverse range
To be able to do something like the following...
Check if start > end
and if so swap both. Don't forget to sort the result in descending order.
The code is self-explanatory.
Result
Couldn't I have done the same thing with a range function? Yes, probably you should do it with a function.
Let this be a mental exercise and a way of making friends with the concept of prototype and proxy.
On This Page