Last active
August 29, 2015 14:04
-
-
Save alastairparagas/15f23e1957c120262198 to your computer and use it in GitHub Desktop.
Hack Reactor Interview History
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
each([1, 2, 3], function (val) { | |
console.log(val); | |
}); | |
// 1 | |
// 2 | |
// 3 | |
var each = function (array, callback) { | |
// Including array.length as variable declaration to "cache" it | |
for(var i=0,arrayLength=array.length; i<arrayLength; i++){ | |
callback(array[i]); | |
} | |
}; | |
map([1, 2, 3, 4], function (val) { | |
return val * 2; | |
}); //=> [2, 4, 6, 8] | |
var map = function (array, callback) { | |
var newArray = []; | |
each(array, functions,.returnedValue) { | |
// modify newArray here | |
newArray.push(callback(returnedValue)); | |
}); | |
return newArray; | |
}; | |
filter([1, 2, 3, 4], function (val) { | |
return val > 2; | |
}); //=> [3, 4] | |
var filter = function (array, truthTest) { | |
var truthyArray = []; | |
each(array, function(returnedValue){ | |
// Ternary wasn't working out, go with the conservative if/else | |
if(truthTest(returnedValue){ | |
truthyArray.push(returnedValue); | |
}else{ | |
// End function execution | |
return; | |
} | |
}); | |
return truthyArray; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment