Skip to content

Instantly share code, notes, and snippets.

@peey
Created September 29, 2014 04:56
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 peey/40ea0d6dba1a21b43138 to your computer and use it in GitHub Desktop.
Save peey/40ea0d6dba1a21b43138 to your computer and use it in GitHub Desktop.
Reverse and re-reverse object key-value maps
var reverseMapFromMap = function(map, callback) {
callback = callback || _.identity;
return _.transform(map, function(reverseMap, one, manyone) {
reverseMap[one] = reversedMap[one] || [];
reverseMap[one].push(callback(manyone));
}, {});
};
var mapFromReverseMap = function(reverseMap, callback) {
callback = callback || _.identity;
return _.transform(reverseMap, function(map, many, one) {
_.forEach(many, function(manyone) {
map[manyone] = callback(one);
});
}, {});
};
//Here's a performance overview of this method versus native and the version not using transform: http://jsperf.com/object-key-value-map-reversal-one-many
//As you can see from the above link, transform method and non-transform method are almost same in performance when it comes to large data, but I chose transform as it looks better to me in terms of readability. Native-only option does not perform so well when operating on large data.
@trumbitta
Copy link

Small typo on #L4?

reversedMap to reverseMap

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment