Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

trumbitta commented Jul 24, 2015

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
You can’t perform that action at this time.