Files
rpg-static-site/utils/filters.js

87 lines
3.0 KiB
JavaScript

const { DateTime, Duration } = require("luxon");
module.exports = {
seasonEpisodeFormat: (_, {
episode,
season,
episodePrefix = "E",
seasonPrefix = "S",
separator = "",
zeroPadding = 2,
}) => {
const episodeNumber = episode ? parseInt(episode, 10)
.toString()
.padStart(zeroPadding, '0') : '';
const seasonNumber = season ? parseInt(season, 10)
.toString()
.padStart(zeroPadding, '0') : '';
return `${seasonPrefix}${seasonNumber}${separator}${episodePrefix}${episodeNumber}`
},
findPageByTag: (tag, collections) => {
// Split the tag to get the collection name and slug
const [collectionName, slug] = tag.split(":");
if (!collectionName || !slug) {
console.error(`Invalid tag format: "${tag}". Expected format "collection:slug".`);
return null;
}
// Ensure the collection exists
const collection = collections[collectionName];
if (!collection) {
console.error(`Collection "${collectionName}" not found in collections.`);
return null;
}
// Search for the page in the inferred collection
// TO-DO: this logic will break once we get into season 10, since season 1 will match 1 and 10
const matchingPage = collection.find(item => item.fileSlug.includes(slug));
// Return the matching page (or null if not found)
return matchingPage || null;
},
extractUniqueTags: (object, tagPrefix = "") => {
// Flatten all pages into a single array of items
let allItems
if (object.pages) {allItems = object.pages.flat()} else { object }
// Extract the desired property from each item
const extractedValues = allItems
.map(item => item.data.tags)
.flat(); // Flatten arrays if the property contains arrays, like tags
// Filter for unique values with the "campaign" prefix
const uniqueValues = [...new Set(extractedValues)]
.filter(tag => tag.startsWith(tagPrefix));
return uniqueValues;
},
formatDate: (date, format = "MMMM d, yyyy") => {
return DateTime.fromJSDate(new Date(date)).toFormat(format);
},
formatDuration: (milliseconds, format = "hh:mm:ss") => {
return Duration.fromMillis(milliseconds).toFormat(format);
},
episodeNumber: (s, episode) => {
return episode ? Number(episode) : Number(s.replace(/[^0-9]/,''))
},
extractSeasonEpisode: (input, property) => {
const regex = /(?:[Ss](?<season>\d{1,2}))?(?:[eE][Pp]?)?(?<episode>\d{1,2})/;
const match = input.match(regex);
if (match) {
const season = match.groups?.season ? parseInt(match.groups.season, 10) : null;
const episode = match.groups?.episode ? parseInt(match.groups.episode, 10) : null;
const result = { season, episode };
return property ? result[property] : result; // Return specific property if requested
}
return property ? null : { season: null, episode: null }; // Return null or full object
},
getEpisodeData: (episodes, season, episode) => {
return episodes.find((e=>e.data.episode==episode && e.data.season==season))?.data
}
}