Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donoage/c59c0e9cd9f1c660fe6526cb2c9f8cf6 to your computer and use it in GitHub Desktop.
Save donoage/c59c0e9cd9f1c660fe6526cb2c9f8cf6 to your computer and use it in GitHub Desktop.
Homework 3 underscore map.js description
// This is the creation of a variable called "_" which is a method
// Stephen: Not a method. variable '_' is an object.
var _ = {
// on this line the first key value is function (so a function within the variable method).
// This function will take to params: list and cbFn
// Stephen: this map() function is a property of '_' object that takes an array and a function reference as their params.
map: function(list, cbFn) {
// within the method's function, there is a new local variable, newArray, which is an empty array
// Stephen: We establish 'newArray', which is an empty array to store the result from forEach() below.
var newArray = [];
// on this line we're showing each element/item created by the parameter "list"
// Stephen: We are invoking forEach() array method on our list parameter.
list.forEach(function(elem, index) {
// creating a new variable using the CbFn parameter and the elements and index generated by the list function
// Stephen: We are invoking our anonoymous function cbFn() to convert each item from array 'list' and,
// storing the result to the variable 'newElem'.
var newElem = cbFn(elem, index);
// the newArray variable is using the push vanilla JS method to create an array using the dynamic variables created by newElem
// Stpehen: we are not creating a new array each time but pushing each converted elem to newArray we established above.
newArray.push(newElem);
});
// Stephen: after iterating and converting each item in 'list', return back the newArray to original function invocation line.
return newArray;
}
};
// this shows the result of the _ variable .map takes 3 objects within an array, converts them using a number parameter,
// multiplies them by three and generates a new array based on the new results.
_.map([1, 2, 3], function(num){ return num * 3; });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment