Forked from bmacmill/gist:76e4b92d2cddbafd8f01713f59d45f7d
Created
April 29, 2017 22:49
-
-
Save donoage/0697fbc640bcd7833865b294d73313d8 to your computer and use it in GitHub Desktop.
03 - Annotating _.map
This file contains hidden or 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
| //we create an object called _ | |
| var _ = { | |
| //the first property is called map it's a method that takes two arguments | |
| //the first argument is list, the second is a call back function | |
| map: function(list, cbFn) { | |
| //this funciton creates a new array | |
| var newArray = []; | |
| //it uses a forEach loop to go through list returning the element i'm not sure what index is doing? | |
| list.forEach(function(elem, index) { | |
| //im not sure why it's setting the cbFn as a variable here instead | |
| //of just putting the cbfn into the new Array | |
| var newElem = cbFn(elem, index); | |
| //here it pushes the neweEleme variable into the new Array | |
| newArray.push(newElem); | |
| }); | |
| //here it returns the new Array | |
| return newArray; | |
| } | |
| }; | |
| //the method is invoked passing in the array 1,2,3 and a new function that multiplies the 1,2,3 by 3 | |
| //reading the underscore.js documentationo, i get that it is "transforming" the array passed in, but I'm failing to see how this is helpful right now... | |
| //it looks like it's an array passin into an array. | |
| //in my defense i put my thumb up sideways as far as how I felt on this!! | |
| _.map([1, 2, 3], function(num){ return num * 3; }); | |
| // => [3, 6, 9] |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
gistfile1.txt, butgistfile1.jssecretgist notpublic. This is up to you.Now onto your comments,
https://gist.github.com/donoage/0697fbc640bcd7833865b294d73313d8#file-gistfile1-js-L9
indexhere isn't really needed because your callback function that's been passed to_.map()takes only 1 argument anyway.https://gist.github.com/donoage/0697fbc640bcd7833865b294d73313d8#file-gistfile1-js-L11-L12
cbFnhere is a function that you passed in initially when you called_.map()and in this line, we're using invoking thatcbFnwithelemas a parameter.cbFnfunction will convert each item in the array you originally passed in ([1,2,3]) and assign the resulting value back to newElem varible. Finally, the value ofnewElemvariable gets pushed intonewArrayvariable, which is an array.https://gist.github.com/donoage/0697fbc640bcd7833865b294d73313d8#file-gistfile1-js-L22
function referencesandcallback functionswork.function referencea lot inFeedrapp. Also more so in your final project.3/4