my ui js class:
JavaScript
x
21
21
1
constructor(){
2
this.profile=document.getElementById("profile");
3
}
4
showRepoInfo(repos){
5
6
this.profile.innerHTML= "";
7
8
repos.forEach(repo => {
9
this.profile.innerHTML += `
10
11
<div id="languages" class="lang">
12
<span class="badge" id="repoStar">${repo.language}</span>
13
<span class="badgee" id="repoSize">${repo.size} KB</span>
14
15
</div>
16
17
`;
18
19
});
20
}
21
how can I print the languages the user is using in their repo and the percentiles of the languages? (i printed the username, name, surname, and repo names I got from the user)
my github js class :
JavaScript
1
18
18
1
class Github{
2
constructor(){
3
this.url = "https://api.github.com/users/";
4
}
5
async getGithubData(username){
6
const responseUser = await fetch(this.url+username);
7
const responseRepo = await fetch(this.url+username + "/repos");
8
9
const userData = await responseUser.json();
10
const repoData = await responseRepo.json();
11
12
return{
13
user:userData,
14
repo:repoData
15
}
16
17
}
18
Advertisement
Answer
I added a new function in your github class and now you can get the language percentage using ${repo.languagesPercentage}
in html.
Note -> 1. This will be an array so you need to add a forEach or convert it into string using toString().
2. It will increase the number of APIs call in case of large repos and it can be optimised by giving a button in html named fetch language %.
JavaScript
1
48
48
1
class Github {
2
constructor() {
3
this.url = "https://api.github.com/users/";
4
this.repoUrl = "https://api.github.com/repos/";
5
}
6
async getGithubData(username) {
7
const responseUser = await fetch(this.url + username);
8
const responseRepo = await fetch(this.url + username + "/repos");
9
10
const userData = await responseUser.json();
11
const repoData = await responseRepo.json();
12
13
// set language percentage of each repo
14
for (let i in repoData) {
15
// get language percentage of repo
16
repoData[i].languagesPercentage = await this.getRepoLanguagePercentage(
17
username,
18
repoData[i].name
19
);
20
}
21
22
return {
23
user: userData,
24
repo: repoData,
25
};
26
}
27
28
async getRepoLanguagePercentage(username, reponame) {
29
const ls = await fetch(
30
this.repoUrl + username + "/" + reponame + "/languages"
31
);
32
33
const languageStats = await ls.json();
34
35
const totalPtsArr = Object.values(languageStats);
36
var sumTotalPts = 0;
37
totalPtsArr.forEach((pts) => {
38
sumTotalPts += pts;
39
});
40
41
const languagesPercentage = {};
42
Object.keys(languageStats).forEach((lang) => {
43
languagesPercentage[lang] = (languageStats[lang] * 100) / sumTotalPts;
44
});
45
46
return languagesPercentage;
47
}
48
}