Created
July 21, 2017 18:39
-
-
Save colonelrascals/77ecc7c025fa37b93e0036d23d7a5ff2 to your computer and use it in GitHub Desktop.
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
//this is how .map works!!! | |
Array.prototype.mapOver = function(callback) { | |
var newArray = [] // since we're returning an array, we'll start with an empty vessel for the contents of that array. | |
for (var i = 0; i < this.length; i ++) { // we're iterating over *the array that is calling* the method. | |
newArray.push(callback(this[i])) // we invoke the callback with an array element as input, and we push the return value onto our new array. | |
} | |
return newArray // .map(), unlike .forEach(), has a return value | |
} | |
console.log(Array.prototype) | |
var someNums = [10,20,3,4] | |
// squareOne is a callback that we will give to mapOver. it takes in an array element, and returns a transformation of it. | |
var squareOne = function(num) { | |
return num * num | |
} | |
var newNums = someNums.mapOver(squareOne) // note that .mapOver(), unlike .forEach(), *returns something*. specifically, it returns a new array. | |
console.log(newNums) | |
console.log('') | |
// [100,400,9,16] | |
var names = ['notsup simble', 'danny noms', 'kristine pristine'] | |
// nameToObj is a callback that we will give to mapOver. it takes in an array element, and returns a transformation of it. | |
var nameToObj = function(name) { | |
var nameParts = name.split(' ') // ['first','last'] | |
return { | |
firstName: nameParts[0], | |
lastName: nameParts[1] | |
} | |
} | |
var nameObjs = names.mapOver(nameToObj) | |
console.log(nameObjs) | |
// [ | |
// {firstName: 'notsup', lastName: 'simble'}, | |
// {firstName: 'danny', lastName: 'noms'}, | |
// {firstName: 'kristine', lastName: 'pristine'} | |
// ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment