Following on from my little experiment with a basic number range syntax in JS, I decided (as with Metho and Turboprop) to generalise the idea and make it into a library that others might find useful (or at least interesting)...
Ranger is a small JS library that allows you to use a range-like syntax with any object. All you need to do is to define a function that builds the required 'range' given a starting and ending object (+ optional extra parameters if you so desire).
So, for example, if you created a range function for Numbers - you could then use it like this:
// create a range of numbers from 1-10constnumbers=1[[...10]]// log the numbers from 6-36[[...3]].forEach(x=>console.log(x))
How to Use
Usage is extremely simple, just import the library and use it to set up the range function on your required object (usually this would be a prototype):
import*asrangerfrom'@jonrandy/js-ranger'constmyRangeFunction=(start,end)=>{// logic to return 'range' here}ranger.attach(myObject,myRangeFunction)
If you pass in optional parameters according to the syntax detailed at the start of this README, they will simply be passed as additional arguments to your range function. Your 'range' making function can return anything - it doesn't have to be an array.
Number Ranges
Also exported by the library as an example of usage is a function called initNumberRangeSyntax that sets up a basic range syntax on the Number prototype - that does pretty much what you would expect. It can also take an additional stepSize parameter that defaults to 1 and decides the (absolute) size of the steps between items in the range:
UPDATE: It has been pointed out that returning an iterator would probably be more efficient and allow for dealing with infinite ranges. That is just as possible with Ranger - simply return a generator function:
// Number ranges as iteratorsattach(Number.prototype,function*(start,end,stepSize=1){constabsStep=stepSize<0?Math.abs(stepSize):stepSizeconststep=start<=end?absStep:-absStepletarr=[],i,d=end>startfor(i=+start;d?i<=end:i>=end;i+=step)yieldi})
Possible Usages
This was written as a general purpose tool that could have any number of potential uses. Some random ideas:
constmyDateRange=date1[[...date2]]constmyRoute=location1[[...location2,{via:location3}]]constmyLine=point1[[...point2]]consttranslator=language1[[...language2]]// could return a function that takes strings in one language and translates to another
Ranger is a small JS library that allows you to use a range-like syntax with any object. All you need to do is to define a function that builds the required 'range' given a starting and ending object (+ optional extra parameters if you so desire).