droff / AO3 Average Word Count

// ==UserScript==
// @name         	AO3 Average Word Count
// @version      	1.0
// @description  	Adds an average word count to fic stats on the Archive.
// @author       	Dr. Off
// @match        	https://archiveofourown.org/*
// @grant        	none
// @license 		MIT
// ==/UserScript==

const statElements = document.querySelectorAll("dl.stats");

for(let statElement of statElements)
{
    let wordsElement = statElement.querySelector("dd.words");
    let chaptersElement = statElement.querySelector("dd.chapters");

    if(wordsElement != undefined && chaptersElement != undefined)
    {
        let chapters = chaptersElement.innerText.split("/");

        let words = parseInt(wordsElement.innerText.replace(",", ""));
        let currentChapterCount = parseInt(chapters[0]);
        let totalChapterCount = chapters[1] != "?" ? parseInt(chapters[1]) : -1;

        if(totalChapterCount == 1) // Skip one shots
            continue;

        let average = Math.ceil(words / currentChapterCount);

        let descriptionTerm = document.createElement("dt");
        descriptionTerm.classList.add("averageChapterLength");
        descriptionTerm.innerText = "Average words per chapter: ";

        let descriptionDetails = document.createElement("dd");
        descriptionDetails.classList.add("averageChapterLength");
        descriptionDetails.innerText = average.toLocaleString('en');

        statElement.appendChild(descriptionTerm);
        statElement.appendChild(descriptionDetails);
    }
}