Last active
September 25, 2015 02:17
-
-
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.
This file contains hidden or 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
// 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