# topologicalOrder

> **topologicalOrder**(`adjacency`): [`TopologicalOrderResult`](/reference/knotkit/graph/type-aliases/topologicalorderresult/)

Defined in: [packages/graph/src/topological-order.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/topological-order.ts#L43)

Order the vertices so every edge points forward, or return one directed cycle that makes that impossible. `O(n + m)` on `compressed-sparse-row` and `adjacency-list`; it walks every row twice, so an `adjacency-matrix` costs `O(n² / 32 + m)` unweighted and `O(n²)` weighted.

Kahn’s algorithm, starting from the vertices with no predecessor in ascending id and taking them first in, first out, so the order is the same on every layout. A cycle is an answer, not a failure: the result says which one it holds. A self-loop is a cycle of one vertex.

## Parameters

### adjacency

[`Adjacency`](/reference/knotkit/graph/interfaces/adjacency/)

## Returns

[`TopologicalOrderResult`](/reference/knotkit/graph/type-aliases/topologicalorderresult/)

## Throws

With code `DIRECTED_GRAPH_REQUIRED` for an undirected graph, where every edge would be a cycle of two vertices; or, from a hand-written `adjacency`, `INVALID_VERTEX` or `INVALID_WEIGHT` for a neighbor or weight it reports, and `INVALID_VERTEX_COUNT` or `INVALID_FLAG` when it misstates its shape.

## Example

```ts
const result = topologicalOrder(dependencies)
if (result.acyclic) build(result.order)
else report(result.cycle)
```
