Show week day and week number

I refactored the code and implemented several optimizations and improvements over the original one. Notable changes include:

  • The code now checks whether the title element already has a date span element before adding a new one. This avoids unnecessary DOM manipulations, improves performance, and prevents potential issues.
  • The date parsing logic has been simplified using the vanilla Date.parse() method and a regular expression to remove ordinal suffixes from the date string. This improves readability and reduces the number of lines of code. Additionally, this change should make the code more flexible in supporting a variety of date formats.
  • The code now calculates the day of the week name and the week number using built-in JavaScript methods, rather than calculating them manually as in the original code. This improves the readability and maintainability of the code, and may also improve performance.
  • Finally, I implemented a MutationObserver to detect changes in the DOM and apply the addExtendedDate function only to newly added title elements. This narrows the scope of elements to check, avoids the need for a setInterval loop, and improves performance while reducing resource usage.

Here it is the final result:

function addExtendedDate(titleElement) {
    // check if element already has date info
    const existingSpan = titleElement.querySelector("span");
    if (existingSpan) return;

    // remove ordinal suffixes from date
    const journalDate = new Date(Date.parse(titleElement.textContent.replace(/(\d+)(st|nd|rd|th)/, "$1")));
    if (!isFinite(journalDate)) return;

    // calculate dates
    const dayOfWeekName = new Intl.DateTimeFormat("default", {weekday: "long"}).format(journalDate);
    const days = Math.ceil((journalDate - new Date(journalDate.getFullYear(), 0, 1)) / 86400000);
    const weekNumber = Math.ceil(days / 7);

    // apply styles
    const dateInfoElement = document.createElement("span");
    dateInfoElement.style = "opacity:0.5;font-size:0.7em";
    dateInfoElement.textContent = ` ${dayOfWeekName}, Week ${weekNumber}`;

    titleElement.appendChild(dateInfoElement);
}

const observer = new MutationObserver(() => {
    document.querySelectorAll("span.title, h1.title").forEach(addExtendedDate);
});

observer.observe(document.getElementById("main-content-container"), {
    attributes: true,
    subtree: true,
    attributeFilter: ["class"],
});

I hope you like it!

11 Likes