Last active
August 29, 2015 14:12
-
-
Save patrickrbc/ddcd61b1a6fa194e9c93 to your computer and use it in GitHub Desktop.
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
var noop = function(){ }; | |
function map(list, func, callback) { | |
var result = new Array(list.length); | |
var count = 0; | |
list.forEach(iterator); | |
function iterator (item, index) { | |
func(item, executed); | |
function executed(err, ret) { | |
if (err) { | |
callback(err); | |
callback = noop; | |
return; | |
} | |
result[index] = ret; | |
count++; | |
if (count === list.length) | |
return callback(null, result); | |
} | |
} | |
} | |
module.exports = map; |
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
function map(list, func, callback) { | |
var result = []; | |
func(list.shift(), cb); | |
function cb (err, ret) { | |
if (err) { | |
callback(err, null); | |
return; | |
} | |
result.push(ret); | |
if (!list.length) { | |
callback(null, result); | |
return; | |
} | |
func(list.shift(), cb); | |
} | |
} | |
module.exports = map; |
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
var assert = require('assert'); | |
var map = require('./map'); | |
describe('Map', function(){ | |
it('should return all values multiplied by 2', function(done) { | |
var arr = [1, 2, 3, 4, 4, 5, 10, -1, 20000, 9090]; | |
function func (a, cb) { | |
var delay = (Math.random()*10).toFixed(0)%3; | |
setTimeout(function () { | |
cb(2*a); | |
}, delay*1000); | |
} | |
function callback (err, result) { | |
if (err) { | |
console.log(err); | |
} else { | |
assert.equal( | |
result.toString(), | |
[2, 4, 6, 8, 8, 10, 20, -2, 40000, 18180].toString() | |
); | |
done(); | |
} | |
} | |
map(arr, func, callback); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment