Created
January 13, 2012 23:53
-
-
Save messa/1609425 to your computer and use it in GitHub Desktop.
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
def connect(*args): | |
maps = list() | |
for collection, keyGetter in args: | |
m = dict() | |
for item in collection: | |
key = keyGetter(item) | |
m[key] = item | |
maps.append(m) | |
result = list() | |
resultKeys = set() | |
for collection, keyGetter in args: | |
for item in collection: | |
key = keyGetter(item) | |
if key in resultKeys: | |
continue | |
resultKeys.add(key) | |
result.append(tuple(m.get(key) for m in maps)) | |
return result | |
def test_connect(): | |
from pprint import pprint, pformat | |
collA = [ | |
{"id": 123, "name": "Hello"}, | |
{"id": 456, "name": "Foo"}, | |
] | |
collB = [ | |
{"id": 456, "data": "def"}, | |
{"id": 123, "data": "abc"}, | |
] | |
result = connect( | |
(collA, lambda x: x["id"]), | |
(collB, lambda x: x["id"])) | |
assert result == [ | |
({"id": 123, "name": "Hello"}, {"id": 123, "data": "abc"}), | |
({"id": 456, "name": "Foo"}, {"id": 456, "data": "def"}), | |
], pformat(result) | |
groups = [ | |
{"groupId": 2, "name": "group 2"}, | |
{"groupId": 1, "name": "group 1"}, | |
{"groupId": 3, "name": "group 3"}, | |
] | |
ads = [ | |
{"groupId": 2, "ad": "some ad"}, | |
] | |
banners = [ | |
{"groupId": 3, "banner": "some banner"}, | |
] | |
result = connect( | |
(groups, lambda g: g["groupId"]), | |
(ads, lambda a: a["groupId"]), | |
(banners, lambda b: b["groupId"])) | |
assert result == [ | |
({"groupId": 2, "name": "group 2"}, {"groupId": 2, "ad": "some ad"}, None), | |
({"groupId": 1, "name": "group 1"}, None, None), | |
({"groupId": 3, "name": "group 3"}, None, {"groupId": 3, "banner": "some banner"}), | |
], pformat(result) | |
if __name__ == "__main__": | |
test_connect() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment