Search code examples
typescriptsortingasynchronousasync-awaitgithub-api

Sort asynchronously with external source


I want to sort my Github Repos by Clones in Typescript
The equivalence in plain js would be

repos.sort(async (a, b) => {
  (await insights.traffic.clones(user, b.name, username, password)).uniques -
    (await insights.traffic.clones(user, a.name, username, password)).uniques;
});

But Array.prototype.sort() doesn't work with async/await

repos is https://api.github.com/users/<user>/repos
insights is import * as insights from 'github-insights' Docs for clones

This would sort the repos in descending order be unique clones

It would get every repo for my account and then sort it with https://api.github.com/repos/<user>/<repo>/traffic/clones

Is there any way to make it work?

Using fast-sort
I came up with this

const sorted = sort(repos).desc([
  async (u) => await (await insights.traffic.clones(user, u.name, username, password)).uniques
]);

but this doesn't sort at all, it just is repos


Solution

  • Try getting all information first, throw it in an array and then sort.

    Pseudo-ish code:

    async function getClonesForRepo(repo) {
     // Do your thing and return a number
    }
    
    const repoClones = new Map();
    for(const repo of repos) {
      repoClones.set(repo.name, await getClonesForRepo(repo));
    }
    
    const sorted = repos.sort(
      (a, b) => repoClones.get(a.name) - repoClones.get(b.name)
    );