Last active
October 19, 2022 14:31
-
-
Save marcusandre/37e16e813d3107f7f70e41389ef7ceb3 to your computer and use it in GitHub Desktop.
Sequential version of Map in continuation passing style
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
type MapHandler<T> = (item: T, index: number, callback: (result: T) => void) => void; | |
type MapDoneHandler<T> = (results: T[]) => void; | |
function map<T>(array: T[], handler: MapHandler<T>, done: MapDoneHandler<T>) { | |
let index = 0; | |
let results: T[] = []; | |
step() | |
function step() { | |
if (index < array.length) { | |
handler(array[index], index, (result) => { | |
results.push(result); | |
index++; | |
step(); | |
}) | |
} else { | |
done(results) | |
} | |
} | |
} | |
map( | |
[1, 2, 3], | |
(item, index, callback) => callback(item * (index + 4)), | |
console.log | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment