Created
November 23, 2021 23:38
-
-
Save gund/04527e9659bfec3960242527a15551d6 to your computer and use it in GitHub Desktop.
Iterate and drain arrays in a nice and concise way using generators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function* drain<T>(arr: T[]): Generator<T> { | |
let item: T | undefined; | |
while ((item = arr.shift())) { | |
yield item; | |
} | |
} | |
const myArray = [1, 2, 3, 4, 5]; | |
console.log('My array before', myArray); | |
for (const item of drain(myArray)) { | |
console.log(`Array item: ${item}, and my array: ${myArray}`); | |
} | |
console.log('My array after', myArray); | |
/* Output: | |
My array before (5) [1, 2, 3, 4, 5] | |
Array item: 1, and my array: 2,3,4,5 | |
Array item: 2, and my array: 3,4,5 | |
Array item: 3, and my array: 4,5 | |
Array item: 4, and my array: 5 | |
Array item: 5, and my array: | |
My array after [] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment