const createRange = (from, to) => Array.from({ length: to - from + 1 }, (_, i) => from + i);
Returns a new array with numeric items in the given range.
Optimised code (Benchmark)
const createRange = (a, b, sign = Math.sign(b - a)) => Array(Math.abs(b - a + sign)).fill().map((_, i) => a + sign * i);
The repository & npm package
You can find the all the utility functions from this series at github.com/martinkr/onelinecode
The library is also published to npm as @onelinecode for your convenience.
The code and the npm package will be updated every time I publish a new article.
Follow me on Twitter: @martinkr and consider to buy me a coffee
Photo by zoo_monkey on Unsplash
Top comments (10)
Maybe can write in single line.
Check the Benchmark). I updated the article and the code with your solution.
Hi,
thank you for your contribution.
Nice code - I'll set up a benchmark.and compare all suggestions so we can find the fastest one.
Cheers!
Cheers!
Not really a one-liner, but it is possible to make a range syntax like this in JS:
If you want to know how - take a look at my post
Amazing series!
More to come when I have some time: String and Array extensions
nice!
Check the Benchmark) if you like.
Hi,
thank you for your contribution.
Nice code - I'll set up a benchmark.
Cheers!