User:Theleekycauldron/orestalk.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
async function get_pages(titles) { // this does something or other to get the pages and shtuss; idk, i don't question it, it works
	var url = "https://en.wikipedia.org/w/api.php";
	let pages;
	var params = {
		action: "query",
		prop: "revisions",
		titles: titles,
		rvprop: "ids",
		rvslots: "main",
		formatversion: "2",
		format: "json",
	};
	url = url + "?origin=*";
	Object.keys(params).forEach(function(key){url += "&" + key + "=" + params[key];});

	let a = fetch(url)
		.then(function(response){return response.json();})
		.then(function(response) {
			pages = response.query.pages;
			
		})
		.catch(function(error){console.log(error);});
	await a;
	return pages;
}

function mean(prob){
	return Math.round(120*(prob["Start"]+prob["C"]*2+prob["B"]*3+prob["GA"]*4+prob["FA"]*5))
}

function median(prob){
	let list = [prob["Stub"],prob["Start"],prob["C"],prob["B"],prob["GA"],prob["FA"]]
	for (let i=0; i<6; i++){
		sum = list.slice(0,i).reduce((partialSum, a) => partialSum + a, 0)
		if (sum+list[i]>0.5){
			return Math.round(100*(i+(0.5-sum)/list[i]))
		}
	}
}

function valToText(val){
	if      (val>=500) return "FA";
	else if (val>=400) return "GA";
	else if (val>=300) return "B";
	else if (val>=200) return "C";
	else if (val>=100) return "Start";
	else               return "Stub";
}

function toMain(page){
  if      (page.slice(0,5)=="Talk:")        return page.slice(5);
  else if (page.slice(0,11)=="Draft_talk:") return "Draft:"+page.slice(11);
  else                                      return page;
}

async function main(){
	let page = mw.config.get('wgPageName')
	if (page.slice(0,5) == "Talk:" || page.slice(0,11) == "Draft_talk:"){
		let pagedata = await get_pages(toMain(page));
		let id = pagedata[0].revisions[0].revid
		url = "https://ores.wikimedia.org/v3/scores/enwiki/"+id+"/articlequality";
		let a = fetch(url)
			.then(function(response){return response.json();})
			.then(function(response) {
				let score = response.enwiki.scores[id].articlequality.score
				let probs = score.probability;
				let mu = mean(probs);
				let max = score.prediction;
				let med = median(probs);
				
				$('#bodyContent').prepend(`<p><i>Mode: ${max} (${Math.round(probs[max]*1000)/10}%)<br/>Mean: ${valToText(mu)} (${mu})<br/>Median: ${valToText(med)} (${med})</i></p>`);
			})
			.catch(function(error){console.log(error);});
		await a;
		
	}
}
main();