Arrays also have a keys method and it's central to this range function working as it should.
Here's how that works:
- It creates an empty (sparse) array of the appropriate length (
Array(max - min + 1)).
- It gets an iterator for the valid indexes of that array (
.keys()). Valid indexes in an arrays are the numbers 0 through the length of the array minus one. (Technically, in specification terms, the indexes of arrays are string property names like "0", "1", etc., but the keys iterator returns numbers because we typically use numbers to index into arrays and that's the more useful value to provide.)
- It spreads the elements from that iterator out into an array (
[...]).
- It creates a new array by mapping each value in the array from #3, adding the
min value to them (.map(i => i + min)).
Note that this creates multiple intermediate arrays and other objects. It's unlikely to matter, but it can be done much more efficiently. For instance, with Array.from as shown by Nina, or even just a simple loop:
const range = (min, max) => {
const result = [];
for (let n = min; n < max; ++n) {
result.push(n); // Or: `result[result.length] = n;` if you want to
// avoid the function call
}
return result;
};
const range = (min, max) => {
const result = [];
for (let n = min; n < max; ++n) {
result.push(n);
}
return result;
};
console.log(range(5, 10));
That's not nearly as cool-looking, though. :-D
But, I probably wouldn't have range return an array at all unless I know for sure that's the end product I'm always going to need. Instead, I'd have it return an iterator:
const range = function*(min, max) {
for (let n = min; n < max; ++n) {
yield n;
}
};
for (const value of range(0, 10)) {
console.log(value);
}
.as-console-wrapper {
max-height: 100% !important;
}
You can always spread it out into an array (or use it with Array.from) if you need an array.
typeof [1, 2, 3]will return'object'keysmethod on an array is fundamentally different from theObject.keysmethod typically used with (non-array) objects. It doesn't return an array of the object's own properties, it returns an iterator for the valid indexes of the array (even if they're unpopulated, which the above relies on).