Skip to content

Instantly share code, notes, and snippets.

@alastairparagas
Last active August 29, 2015 14:04
Show Gist options
  • Save alastairparagas/15f23e1957c120262198 to your computer and use it in GitHub Desktop.
Save alastairparagas/15f23e1957c120262198 to your computer and use it in GitHub Desktop.
Hack Reactor Interview History
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