Group reachable nodes in a directed graph by BFS hop count
A social app shows “people you may know” grouped by distance: people you follow, people they follow, and so on. Follows are one-way, so the network is a directed graph. The suggestion panel needs every reachable person grouped by the fewest number of hops it takes to reach them, in a stable order so the list does not jump around between renders.
Implement hopLevels(graph, start, maxHops).
hopLevels(graph, start, maxHops = Infinity) // => string[][]
graph is an object whose keys are node ids. graph[id] is an array of the ids that id links to (its outgoing edges).'constructor' or 'toString'.start is always a node, even if it is not a key of graph.maxHops is a non-negative integer or Infinity.0 is [start]. Level d lists the nodes whose shortest path from start has exactly d edges.0 to maxHops are returned.const follows = {
ana: ['ben', 'cara'],
ben: ['dev'],
cara: ['dev', 'eli'],
dev: ['fay'],
};
hopLevels(follows, 'ana');
// => [['ana'], ['ben', 'cara'], ['dev', 'eli'], ['fay']]
hopLevels(follows, 'ana', 1); // => [['ana'], ['ben', 'cara']]
hopLevels(follows, 'dev'); // => [['dev'], ['fay']] (edges are one-way)
hopLevels(follows, 'eli'); // => [['eli']] (eli has no key)
hopLevels({}, 'zoe'); // => [['zoe']]