AI solution for JavaScript Coding Question on BFE.dev
39. implement range()
There are several ways to implement range()
function in JavaScript. Here are a few possible solutions:
- Using a generator function:
function* range(from, to) { for (let num = from; num <= to; num++) { yield num; }}
This implementation uses a generator function, which allows us to create an iterable object that generates a sequence of numbers on the fly. The yield
keyword is used to produce a value from the generator each time it is called, and the for
loop is used to generate all the numbers in the range from from
to to
.
We can use this range()
function with a for...of
loop as shown in the example:
for (let num of range(1, 4)) { console.log(num); }// Output: 1, 2, 3, 4
- Using
Array.from()
method:
function range(from, to) { return Array.from({ length: to - from + 1 }, (_, i) => from + i);}
This implementation uses the Array.from()
method to create an array of numbers in the range from from
to to
. The first parameter to Array.from()
is an object that has a length
property equal to the number of elements in the resulting array. The second parameter is a map function that generates the numbers in the range based on their index in the array.
We can use this range()
function with a for...of
loop as shown in the example:
for (let num of range(1, 4)) { console.log(num); }// Output: 1, 2, 3, 4
- Using ES6 spread operator:
function range(from, to) { return [...Array(to - from + 1)].map((_, i) => from + i);}
This implementation is similar to the previous one, but it uses the ES6 spread operator (...
) to convert the array returned by Array()
constructor into a list of arguments passed to map()
method.
We can use this range()
function with a for...of
loop as shown in the example:
for (let num of range(1, 4)) { console.log(num); }// Output: 1, 2, 3, 4
All of these implementations produce the same output in the given example. You can choose the one that you find more readable and suits your needs.