Skip to content

Instantly share code, notes, and snippets.

@iamsaief
Last active March 20, 2024 17:46
Show Gist options
  • Save iamsaief/567e4d98bc571cf78effaa444cc1475c to your computer and use it in GitHub Desktop.
Save iamsaief/567e4d98bc571cf78effaa444cc1475c to your computer and use it in GitHub Desktop.
Frequently used js utility functions

Frequently used js utility functions

getRandomUUID()
getFluidFontSize()
getFirstNWords()
getFormattedTimeDiff()
cn()
/**
* Combines class names into a string
* @param {...string} classes - class names
* @returns {string} Combined class name
*/
export const cn = (...classes) => {
return classes.filter(Boolean).join(" ");
};
/**
* Gets the first N words from an article.
*
* @param {string} article The article text.
* @param {number} numWords The number of words to extract (defaults to 20).
* @returns {string} The first N words from the article.
*/
export function getFirstNWords(article, numWords) {
// Split the article into an array of words
const words = article.split(" ");
// Limit the number of words based on input and article length
const firstNWords = words.slice(0, Math.min(words.length, numWords));
// Join the first N words back into a string
const snippet = firstNWords.join(" ");
return snippet;
}
/**
* Returns a clamp expression for fluid typography based on the given parameters.
* @param {string} minFontSize - The minimum font size in pixels.
* @param {string} maxFontSize - The maximum font size in pixels.
* @param {string} [minViewport='768px'] - The minimum viewport width in pixels.
* @param {string} [maxViewport='1400px'] - The maximum viewport width in pixels.
* @returns {string} A clamp expression that can be used in CSS.
*/
export function getFluidFontSize(minFontSize, maxFontSize, minViewport = '768px', maxViewport = '1400px') {
// Convert the parameters to numbers
minFontSize = parseFloat(minFontSize);
maxFontSize = parseFloat(maxFontSize);
minViewport = parseFloat(minViewport);
maxViewport = parseFloat(maxViewport);
let fontSizeInRem = minFontSize / 16;
let fontSizeDiff = maxFontSize - minFontSize;
let viewportDiff = maxViewport - minViewport;
// Return the clamp expression as a string
return `clamp(${minFontSize}px, calc(${fontSizeInRem}rem + ${fontSizeDiff} * ((100vw - ${minViewport}px) / ${viewportDiff})), ${maxFontSize}px)`;
}
/**
* Converts a datetime string into to a formatted date compared to current time.
*
* @param {string} inputDatetime A datetime string in the format YYYY-MM-DDTHH:MM:SS.fffZ
* @returns {string} A string representing the time difference in a readable format.
*/
export function getFormattedTimeDiff(inputDatetime) {
let inputDt;
try {
// Parse the input datetime string
inputDt = new Date(inputDatetime);
} catch (ValueError) {
return "Invalid datetime format.";
}
const now = new Date();
const delta = Math.abs(now - inputDt); // Take absolute value of difference
const seconds = delta / 1000;
// Define units and their corresponding thresholds
const units = [
["years", 31536000],
["months", 2592000],
["weeks", 604800],
["days", 86400],
["hours", 3600],
["minutes", 60],
];
// Iterate through units to find the best fit
for (const [unit, threshold] of units) {
if (seconds >= threshold) {
const value = Math.floor(seconds / threshold);
if (unit === "months") {
// Format date for "June 28, 2018" format
const options = { year: "numeric", month: "long", day: "numeric" };
return inputDt.toLocaleDateString("en-US", options);
} else {
return `${value} ${unit} ago`;
}
}
}
// If less than a minute, return "just now"
return "just now";
}
/**
* Generates a UUID in the version 4 format.
* @returns {string} A UUID string.
*/
export function getRandomUUID() {
// Create an array of hexadecimal digits
const hexDigits = '0123456789abcdef'.split('');
// Create an array of 36 characters
const chars = new Array(36);
// Loop through the characters array
for (let i = 0; i < 36; i++) {
// If the index is 8, 13, 18, or 23, insert a hyphen, Otherwise, insert a random hexadecimal digit
if (i === 8 || i === 13 || i === 18 || i === 23) {
chars[i] = '-';
} else {
chars[i] = hexDigits[Math.floor(Math.random() * 16)];
}
}
return chars.join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment