Last active
August 29, 2015 14:06
-
-
Save christopherhill/da7e45c198cbad2d76e6 to your computer and use it in GitHub Desktop.
Exercise (get second degree connections from graph data)
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 graph = { | |
nodes: | |
[{ | |
userId: 'chill', | |
city: 'Sonoma' }, | |
{ | |
userId: 'sjobs', | |
city: 'Mountain View' }, | |
{ | |
userId: 'bgates', | |
city: 'Sonoma' }, | |
{ | |
userId: 'someguy', | |
city: 'Mountain View' | |
}, | |
{ | |
userId: 'someotherguy', | |
city: 'Mountain View' | |
}, | |
{ | |
userId: 'ahill', | |
city: 'Somewhere over the Rainbow' | |
}, | |
{ | |
userId: 'randomSJguy', | |
city: 'San Jose' | |
}], | |
connections: | |
[ | |
{ | |
userId1: 'chill', | |
userId2: 'bgates', | |
userId3: 'sjobs', | |
userId4: 'someotherguy' }, | |
{ | |
userId1: 'sjobs', | |
userId2: 'chill' }, | |
{ | |
userId1: 'bgates', | |
userId2: 'chill' }, | |
{ | |
userId1: 'sjobs', | |
userId2: 'bgates' } | |
] | |
}; | |
/* prepare data method generates following structure: | |
{ | |
'chill' : | |
{ | |
city: 'San Jose', | |
connections: [] | |
} | |
} | |
*/ | |
function prepareData(data) { | |
var result = {}; | |
for (var i in data.nodes) { | |
var key = data.nodes[i].userId; | |
result[key] = {}; | |
result[key].city = data.nodes[i].city; | |
result[key].connections = []; | |
for (var j in data.connections) { | |
if (data.connections[j].userId1 === data.nodes[i].userId) { | |
for (var k in data.connections[j]) { | |
if (k !== 'userId1') { | |
result[key].connections.push(data.connections[j][k]); | |
} | |
} | |
} | |
} | |
} | |
return result; | |
}; | |
function secondDegree(id, city, data) { | |
var firstDegrees = data[id].connections, | |
results = []; | |
for (var i in firstDegrees) { | |
var curFirstDegree = firstDegrees[i], | |
secondDegrees = data[curFirstDegree].connections, | |
curCity, inFirstDegrees, inSecondDegrees; | |
for (var j in secondDegrees) { | |
curName = secondDegrees[j]; | |
curCity = data[secondDegrees[j]].city; | |
inFirstDegrees = firstDegrees.indexOf(id); | |
inSecondDegrees = secondDegrees.indexOf(id); | |
if (curName !== id && curName !== curFirstDegree && | |
curCity === city && inFirstDegrees === -1) { | |
results.push(secondDegrees[j]); | |
} | |
} | |
} | |
return results; | |
} | |
var data = prepareData(graph); | |
var location = 'Mountain View'; | |
var results = secondDegree('bgates', location, data); | |
console.log('Matching second degree connections in %s: ', location, results); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment