Last active
December 22, 2015 16:48
-
-
Save chreke/6501383 to your computer and use it in GitHub Desktop.
SQL-like "join" function as an underscore.js mixin
This file contains hidden or 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
(function () { | |
/* | |
TODO: Support more join types? | |
TODO: Support single key? | |
*/ | |
var crossProduct = function(objects1, objects2) { | |
var objects = []; | |
for (var i = 0; i < objects1.length; i++) { | |
for (var j = 0; j < objects2.length; j++) { | |
objects.push(_.extend({}, objects1[i], objects2[j])); | |
} | |
} | |
return objects; | |
}; | |
var leftJoin = function(collectionA, collectionB, keyA, keyB) { | |
var indexedA = _.groupBy(collectionA, keyA), | |
indexedB = _.groupBy(collectionB, keyB), | |
keys = _.keys(indexedA); | |
return _.reduce(keys, function(acc, x) { | |
var objsA = indexedA[x], | |
objsB = indexedB[x] || [{}]; | |
return acc.concat(crossProduct(objsA, objsB)); | |
}, []); | |
}; | |
_.mixin({ | |
leftJoin: leftJoin | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment