Skip to content

Instantly share code, notes, and snippets.

@marcusandre
Last active October 19, 2022 14:31
Show Gist options
  • Save marcusandre/37e16e813d3107f7f70e41389ef7ceb3 to your computer and use it in GitHub Desktop.
Save marcusandre/37e16e813d3107f7f70e41389ef7ceb3 to your computer and use it in GitHub Desktop.
Sequential version of Map in continuation passing style
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