// Demonstrating several ways to build a list containing a range of numbers.
// Each function shows a different style that experienced developers commonly use.
// Build a list using Array.from().
// This is concise, expressive, and uses a built‑in constructor.
function makeRangeArrayFrom(start, end) {
// Array.from() can take a mapping function that receives the index.
return Array.from({ length: end - start }, (_, i) => start + i);
}
// Build a list using a simple for‑loop.
// Clear and flexible; works in any environment.
function makeRangeLoop(start, end) {
const values = [];
for (let n = start; n < end; n++) {
values.push(n);
}
return values;
}
// Build a list using a generator function.
// Useful when you want lazy iteration or custom stepping.
function* rangeGenerator(start, end) {
for (let n = start; n < end; n++) {
yield n;
}
}
function makeRangeFromGenerator(start, end) {
return [...rangeGenerator(start, end)];
}
// Build a list using Array.fill() + map.
// Shows how to repurpose an existing array.
function makeRangeFillMap(start, end) {
return new Array(end - start)
.fill(0)
.map((_, i) => start + i);
}
// Print a list for demonstration.
function show(label, values) {
console.log(`${label}:`, values);
}
function main() {
const a = makeRangeArrayFrom(1, 10);
const b = makeRangeLoop(1, 10);
const c = makeRangeFromGenerator(1, 10);
const d = makeRangeFillMap(1, 10);
show("Array.from()", a);
show("loop", b);
show("generator", c);
show("fill + map", d);
}
main();
/*
run:
Array.from(): [
1, 2, 3, 4, 5,
6, 7, 8, 9
]
loop: [
1, 2, 3, 4, 5,
6, 7, 8, 9
]
generator: [
1, 2, 3, 4, 5,
6, 7, 8, 9
]
fill + map: [
1, 2, 3, 4, 5,
6, 7, 8, 9
]
*/