💾*list()

JSiterationcustom generators ⟩ *list()

💾 replit:list()

👉 compare: *closedRange(), ClosedRange

// ⭐️ list()  (generator function)
function* list(count, {start=0, step=1}={}){
    for(let i = 0; i < count; i++){
        yield start + step * i;
    }
}

💈範例:

// ⭐️ for-of loop
for (const i of list(5)) {
    sum += i;
}                                // sum = 10

// ⭐️ generator object -> array
[...list(5)],                           // [ 0, 1, 2, 3, 4 ]
[...list(5, {start: 1})],               // [ 1, 2, 3, 4, 5 ]
[...list(5, {step: 2})],                // [ 0, 2, 4, 6, 8 ]
[...list(5, {start: 2, step: -1})],     // [ 2, 1, 0, -1, -2 ]

Last updated