Last active
December 7, 2023 00:43
-
-
Save marsgpl/8f8f742d448fdb2767e1b5f8253f2479 to your computer and use it in GitHub Desktop.
asyncMapper.ts
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
// write async generator to return N random strings per call | |
// add parameter to limit total amount of strings returned by generator | |
// write async mapper that accepts async generator as argument and | |
// a callback that is applied for every generator result | |
// mapper should return all generator results as array | |
async function getLinesTotal() { | |
return 8 | |
} | |
async function getLines( | |
offset: number, | |
limit: number, | |
linesTotal: number, | |
): Promise<string[]> { | |
return Array.from(Array(Math.min(linesTotal - offset, limit)), | |
(_, i) => `line #${offset + i + 1}`) | |
} | |
async function *linesGen(pageSize: number): AsyncGenerator<string[], string[]> { | |
const linesTotal = await getLinesTotal() | |
let linesReturned = 0 | |
while (linesReturned < linesTotal) { | |
const lines = await getLines(linesReturned, pageSize, linesTotal) | |
linesReturned += lines.length | |
if (lines.length < pageSize || linesReturned === linesTotal) { | |
return lines | |
} else { | |
yield lines | |
} | |
} | |
return [] | |
} | |
const lines = linesGen(3) | |
async function asyncMapper<T>( | |
generator: AsyncGenerator<T, T, void>, | |
mapper: (chunk: T) => T, | |
): Promise<T[]> { | |
const mapped: T[] = [] | |
while (true) { | |
const result = await generator.next() | |
mapped.push(mapper(result.value)) | |
if (result.done) break | |
} | |
return mapped | |
} | |
asyncMapper<string[]>(lines, lines => | |
lines.map(line => | |
line.split('').reverse().join(''))) | |
.then(mapped => mapped.flat()) | |
.then(console.log) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment