Skip to content

Instantly share code, notes, and snippets.

@johntran
Last active March 9, 2016 08:50
Show Gist options
  • Save johntran/b1f06879ca51e796cdd9 to your computer and use it in GitHub Desktop.
Save johntran/b1f06879ca51e796cdd9 to your computer and use it in GitHub Desktop.
//Re-writing Underscore and LoDash functions.
var forEach = function(collection, callback) {
for (var key in collection) {
callback(collection[key]);
}
};
var map = function(collection, callback) {
var result = [];
forEach(collection, function(value) {
result.push(callback(value));
});
return result;
}
var reduce = function(collection, callback, initialValue) {
var result;
var isUndefined = typeof initialValue == typeof undefined;
var isNull = typeof initialValue == typeof null;
var hasInitialValue = false;
if (isUndefined == false && isNull == false) {
hasInitialValue = true;
result = initialValue;
} else {
result = collection[0];
}
var index = 0;
forEach(collection, function(value) {
if (index === 0 && !hasInitialValue) {
index++;
return;
}
result = callback(result, value);
});
return result;
};
var filter = function(collection, callback){
var result = [];
forEach(collection, function(value){
if(callback(value)===true){
result.push(value);
}
});
return result;
};
/** Runs a function only once.
* var test = function(){
* console.log("beep")
* return 22;
*}
* var woo = once(test);
* woo();
* this will return "beep" and 22.
* woo();
* this will return 22.
*/
var once = function (callback) {
cachedResult = [];
return function() {
if (typeof cachedResult[0] === 'undefined') {
cachedResult.push(callback());
return cachedResult;
}
return cachedResult;
}
}
// New Reduce Implementation
var reduce = function(collection, callback, initialValue) {
var acc;
if (!initialValue && !collection) {
return 'There is no initialValue or collection';
}
if (!callback) {
return 'There is no callback';
}
if (initialValue) {
acc = initialValue
} else {
acc = collection[0]
collection = collection.slice(1)
}
if (collection) {
forEach(collection, function(element){
acc = callback(acc, element)
})
}
return acc
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment