Created
September 29, 2014 04:56
-
-
Save peey/40ea0d6dba1a21b43138 to your computer and use it in GitHub Desktop.
Reverse and re-reverse object key-value maps
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 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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Small typo on #L4?
reversedMap to reverseMap