Skip to content

Instantly share code, notes, and snippets.

@briandk
Last active August 29, 2015 14:11
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 briandk/e561fc59e81eaebd2adc to your computer and use it in GitHub Desktop.
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.
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