Skip to content

Instantly share code, notes, and snippets.

@ithinkihaveacat
Last active September 25, 2015 02:17
Show Gist options
  • Save ithinkihaveacat/846521 to your computer and use it in GitHub Desktop.
Save ithinkihaveacat/846521 to your computer and use it in GitHub Desktop.
Map an array, where the map function, and the result of the map, are asynchronous.
// SYNCHRONOUS MAP
function smap(src, fn) {
if (src.length == 0) {
return [];
} else {
return [fn(src[0])].concat(smap(src.slice(1), fn));
}
}
function sadd(n) {
return n + 1;
}
console.log(smap([2, 3, 4], sadd));
// ASYNC (BUT ORDERED/SERIAL) MAP
function amap(arr, fn, callback) {
if (arr.length == 0) {
callback([]);
} else {
fn(arr[0], function(v) {
amap(arr.slice(1), fn, function (list) {
callback([v].concat(list));
})
});
}
}
function aadd(n, callback) {
callback(n + 1);
}
amap([2, 3, 4], aadd, console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment