Advent of Code Day Navigation Links

This adds forward and backwards links to each day's page.

  1. // ==UserScript==
  2. // @name Advent of Code Day Navigation Links
  3. // @namespace Violentmonkey Scripts
  4. // @match https://adventofcode.com/*/day/*
  5. // @grant none
  6. // @version 1.0
  7. // @author -
  8. // @description This adds forward and backwards links to each day's page.
  9. // @author josh
  10. // @namespace https://gitlab.com/userscript4/advent-of-code-day-nav
  11. // @supportURL https://gitlab.com/userscript4/advent-of-code-day-nav/-/issues
  12. // @license MIT
  13. // ==/UserScript==
  14.  
  15. /**
  16. * Return the url of the requested day.
  17. * If less than 1 or greater than 25 provide a url to the overview page.
  18. * @param {number} day
  19. * @returns {string} A url to the requested day
  20. */
  21. function makeURL(day) {
  22. if (day < 1 || day > 25) {
  23. return window.location.href.replace(/\/day\/.*/, '');
  24. }
  25. return window.location.href.replace(/(?<=\/day\/).*/, day);
  26. }
  27.  
  28. /**
  29. * Create an anchor tag.
  30. * @param {number} day
  31. * @param {string} text
  32. * @returns {HTMLAnchorElement}
  33. */
  34. function makeAnchor(day, text) {
  35. const anchor = document.createElement('a');
  36. anchor.href = makeURL(day);
  37. anchor.textContent = text;
  38. return anchor
  39. }
  40.  
  41. /**
  42. * Find the title, extract the day number, replace the `---` with links.
  43. */
  44. function addNavigationLinks() {
  45. const title = document.querySelector('article.day-desc > h2');
  46. const currentDay = parseInt(title.textContent.match(/(?<=Day )[0-9]+(?=:)/)[0]);
  47. title.textContent = title.textContent.match(/^--- (.*?) ---$/)[1];
  48. title.prepend(makeAnchor(currentDay - 1, '<-- '));
  49. title.append(makeAnchor(currentDay + 1, ' -->'));
  50. }
  51.  
  52. addNavigationLinks();