Factor out the indexing part to a util fn.