Last active
August 29, 2015 14:11
-
-
Save briandk/e561fc59e81eaebd2adc to your computer and use it in GitHub Desktop.
Figuring out how to pass an external context to a JavaScript map function. Why? Say you want a function that operates element-wise on an array, but generates results that it needs to add to some outside object, like an array or a dictionary.
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
var myDictionary = { | |
rocket: 'Atlas V', | |
spaceport: 'Cape Canaveral', | |
astronauts: [ | |
'Brian', | |
'Wil' | |
] | |
}; | |
var getValueFromExternalDictionary = function (currentKey, indexOfCurrentKey) { | |
'use strict'; | |
return (this[currentKey]) // the value of "this" will be supplied as an external context in | |
// the .map() call | |
}; | |
var keysOfInterest = [ | |
'rocket', | |
'astronauts' | |
]; | |
keysOfInterest.map(getValueFromExternalDictionary, myDictionary); | |
// ^ Will return ["Atlas V", Array[2]0: "Brian"1: "Wil"length: 2__proto__: Array[0]] | |
/* | |
Below we change the keys of interest and change their order. | |
This case is to test whether the function is just chugging along the array, | |
or whether it's actually performing the lookup in the dictionary we supplied as | |
an external context | |
*/ | |
keysOfInterest = [ | |
'spaceport', | |
'rocket' | |
]; | |
keysOfInterest.map(getValueFromExternalDictionary, myDictionary); | |
// returns ["Cape Canaveral", "Atlas V"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment