Jump to content

User:Habst/getInfoboxNationals.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.
pret=window.location.href.split('/').slice(0, 3).join('/')
id=window.location.href.split('/').slice(-2).join('/')
window.authorization??=new DOMParser().parseFromString(await (await fetch('/beta')).text(), 'text/html').querySelector('script:not([src])').innerText.split("'")[1]
demonym = {
  DEN: 'Danish',
  BLR: 'Belarusian',
  SWE: 'Swedish',
  CHN: 'Chinese',
  KEN: 'Kenyan',
  USA: 'USA',
  BDI: 'Burundian',
  ITA: 'Italian',
  UGA: 'Ugandan',
  AUS: 'Australian',
  GBR: 'British',
  FRA: 'French',
  ETH: 'Ethiopian',
  JPN: 'Japanese',
  TPE: 'Taiwanese',
  ROU: 'Romanian',
  TUR: 'Turkish',
  TUN: 'Tunisian',
  ALG: 'Algerian',
  MAR: 'Moroccan',
  BAR: 'Barbados',
  TTO: 'Trinidad and Tobago',
  JAM: 'Jamaican',
  GUA: 'Guatemalan',
  CRC: 'Costa Rican',
};
outdoor = '';
athletics = 'Athletics';
out = '| nationals = {{ubl\n';
exists=async pg=>{
  const r = await fetch(`https://xtools.wmcloud.org/api/page/articleinfo/en.wikipedia.org/${pg}?format=json&uselang=en`);
  return r.status === 200;
}
function nth(n){return n ? ["st","nd","rd"][((n+90)%100-10)%10-1]||"th" : ''}
window.seasons = (await (await fetch(pret+`/api/athletes/${id}/seasons`, {
  headers: { authorization }
})).json()).data.map(s => +s.value).sort((a, b) => a - b);
window.results ??= {};
for (const season of seasons) {
  const data = window.results[season] ??= await (await fetch(pret+`/api/athletes/${id}/season/${season}`, {
    headers: { authorization }
  })).json();
  const results = data.templates?.[0].divs[0].tables.flatMap(table => table.body.map(res => ({...res, title: table.title.replace('One Mile', 'Mile run').replace('Steeplechase', `s'chase`).split(' ').map((w, i) => i ? w[0].toLowerCase() + w.slice(1) : w).join(' '), cat: res.pos?.split('-')[1] }))).sort((a, b) => new Date(a.date) - new Date(b.date)).filter(res => ['NC', 'NR', 'NC-j', 'NR-j', 'NC-y', 'NC-w', 'NCAA', 'NG', 'OT'].includes(res.competition) && !['h', 's', 'r', 'q'].some(rnd => res.pos?.includes(rnd))) ?? [];
  for (const res of results) {
    if (res.dontCount) continue;
    const idx = results.indexOf(res);
    const isXC = res.title === 'Cross country';
    if (results[idx - 1]?.competitionId !== res.competitionId || results[idx - 1]?.cat !== res.cat) {
      if (res.competition === 'NCAA') {
        out += `|'''[[${season} NCAA Division I ${isXC ? 'Cross Country' : `${res.indoor ? 'Indoor' : 'Outdoor'} Track and Field`} Championships|${season} ${isXC ? 'NCAA XC' : res.indoor ? 'NCAA Indoors' : 'NCAAs'}]]'''\n`;
      } else if (res.competition === 'NG') {
        const athng = `Athletics at the ${season} National Games of China`;
        out += `|'''[[${await exists(athng) ? athng : `${season} National Games of China`}|${season} National Games]]'''\n`;
      } else {
        const titleWords = [season, demonym[res.venueCountry]];
        if (res.indoor) titleWords.push('Indoor');
        if (res.pos?.includes('-')) titleWords.push(res.pos.endsWith('-22') ? 'U23' : res.pos.endsWith('-19') ? 'U20' : res.pos.endsWith('-17') ? 'U18' : res.pos.endsWith('-16') ? 'U17' : res.pos.endsWith('-15') ? 'U16' : 'Junior');
        else if (!res.indoor) titleWords.push('Champ');
        titleWords[titleWords.length - 1] += 's';
        if (res.pos?.includes('-')) {
          out += `|'''${titleWords.join(' ')}'''\n`;
        } else {
          const meetTitle = `${demonym[res.venueCountry]}${res.indoor ? ' Indoor' : outdoor ? ` ${outdoor}` : ''} ${athletics} Championships`;
          const yearTitle = season + ' ' + meetTitle;
          if (await exists(yearTitle)) out += `|'''[[${yearTitle}|${titleWords.join(' ')}]]'''\n`;
          else {
            titleWords.shift();
            out += `|'''${season} [[${meetTitle}|${titleWords.join(' ')}]]'''\n`;
          }
        }
      }
    }
    const pl = +res.pos1;
    const evt = isXC ? `Cross country running|${res.eventDistance}km XC` : res.title.replace('Mile, road', 'Road mile');
    out += `|{{bull}} [[${evt}]], ${pl || res.result}${nth(pl)}${{1:' {{GoldMedal}}',2:' {{SilverMedal}}',3:' {{BronzeMedal}}'}[pl] ?? ''}\n`
  }
}
out += '}}';
console.log(out);