@akadenia/helpers
Version:
Akadenia helpers
340 lines (339 loc) • 12.4 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.abbreviateNumber = exports.isValidEmail = exports.enforceCharacterLimit = exports.capitalizeText = exports.handleNullDisplay = exports.convertCamelToSnakeCase = exports.convertSnakeToCamelCase = exports.pluralizeOnCondition = exports.replaceUnderscoreWithSpaces = exports.replaceSpacesWithUnderscore = exports.fileNameFromPath = exports.truncateText = exports.formatPosition = exports.uuidv4 = exports.convertKeyCasing = void 0;
exports.convertCamelToKebabCase = convertCamelToKebabCase;
exports.convertKebabToCamelCase = convertKebabToCamelCase;
exports.generateAcronym = generateAcronym;
exports.isAcronym = isAcronym;
exports.acronymToKebabCase = acronymToKebabCase;
exports.generateIDFromWord = generateIDFromWord;
exports.generateWordFromId = generateWordFromId;
exports.generateSlugFromWordsWithID = generateSlugFromWordsWithID;
exports.extractIDfromSlug = extractIDfromSlug;
const _1 = require("./");
// Internal Helper Functions At The Top
/**
*
* @function
* @param {T} input - The string, object, or array of objects that needs to have its casing changed
* @param {"toSnakeCase" | "toCamelCase"} type - The type of casing the string, object, or array of objects should be converted to (snake_case or camelCase)
* @returns {T} - A new string, object, or array of objects in the specified casing
*/
const convertKeyCasing = (input, type) => {
if (typeof input === "string") {
const transformedString = type === "toSnakeCase"
? input.replace(/([A-Z0-9])/g, "_$1").toLowerCase()
: input.toLowerCase().replace(/(_\w)/g, (m) => m[1].toUpperCase());
return transformedString;
}
else if (_1.ObjectHelpers.isPureObject(input)) {
const newObj = {};
for (const key in input) {
if (Object.prototype.hasOwnProperty.call(input, key)) {
const newKey = type === "toSnakeCase" ? key.replace(/([A-Z])/g, "_$1").toLowerCase() : key.replace(/(_\w)/g, (m) => m[1].toUpperCase());
if (_1.ObjectHelpers.isPureObject(input[key]) || Array.isArray(input[key])) {
newObj[newKey] = (0, exports.convertKeyCasing)(input[key], type);
}
else {
newObj[newKey] = input[key];
}
}
}
return newObj;
}
else if (Array.isArray(input)) {
return input.map((item) => (0, exports.convertKeyCasing)(item, type));
}
return input;
};
exports.convertKeyCasing = convertKeyCasing;
/**
*
* @function
* @returns {string} - A randomly generated string.
*/
const uuidv4 = () => {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
const r = (Math.random() * 16) | 0;
const v = c === "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
};
exports.uuidv4 = uuidv4;
/**
*
* @function
* @param {number} position - A position number.
* @returns {string} - A string representing the position with the appropriate suffix (st, nd, rd, or th) e.g "1st", "2nd", "3rd", "4th", etc.
*/
const formatPosition = (position) => {
let postfix = "th";
if (position === 1) {
postfix = "st";
}
else if (position === 2) {
postfix = "nd";
}
else if (position === 3) {
postfix = "rd";
}
return `${position}${postfix}`;
};
exports.formatPosition = formatPosition;
/**
*
* @function
* @param {string} text - The text to be truncated
* @param {number} characterLimit - The maximum number of characters that the text can have
* @returns {string} - The truncated text with "..." added at the end if the text has exceeded the character limit
*/
const truncateText = (text, characterLimit) => text.length > characterLimit ? text.substring(0, characterLimit - 3) + "..." : text;
exports.truncateText = truncateText;
/**
*
* @function
* @param {string} path - The path of the file
* @returns {string} - The file name
*/
const fileNameFromPath = (path) => path.substring(path.lastIndexOf("/") + 1);
exports.fileNameFromPath = fileNameFromPath;
/**
*
* @function
* @param {string} s - The string that needs to have spaces replaced with underscores
* @returns {string} - The string with spaces replaced with underscores
*/
const replaceSpacesWithUnderscore = (s) => (s === null || s === void 0 ? void 0 : s.trim().replace(/\s/g, "_")) || "";
exports.replaceSpacesWithUnderscore = replaceSpacesWithUnderscore;
/**
*
* @function
* @param {string} s - The string that needs to have underscores replaced with spaces
* @returns {string} - The string with underscores replaced with spaces
*/
const replaceUnderscoreWithSpaces = (s) => (s === null || s === void 0 ? void 0 : s.trim().replace(/_/g, " ")) || "";
exports.replaceUnderscoreWithSpaces = replaceUnderscoreWithSpaces;
/**
*
* @function
* @param {string} word - The word that needs to be pluralized
* @param {boolean} condition - The condition that determines if the word needs to be pluralized
* @returns {string} - The word with "s" added to the end if the condition is true
*/
const pluralizeOnCondition = (word, condition) => {
return condition ? `${word}s` : word;
};
exports.pluralizeOnCondition = pluralizeOnCondition;
/**
* @function
* @param {Object | Array<Object> | string} data - The object or array of objects to convert key cases
* @returns {Object | Array<Object> | string} - The object or array of objects with the keys in camelCase
*/
const convertSnakeToCamelCase = (data) => {
return (0, exports.convertKeyCasing)(data, "toCamelCase");
};
exports.convertSnakeToCamelCase = convertSnakeToCamelCase;
/**
* @function
* @param {Object | Array<Object> | string} data - The object or array of objects to convert key cases
* @returns {Object | Array<Object> | string} - The object or array of objects with the keys in snake_case
*/
const convertCamelToSnakeCase = (data) => {
return (0, exports.convertKeyCasing)(data, "toSnakeCase");
};
exports.convertCamelToSnakeCase = convertCamelToSnakeCase;
/**
* Convert camel case to kebab case
* @function
* @param {string} word - The word needed to be converted to kebab case from camel case
* @returns {string} - The word returned as kebab case
*/
function convertCamelToKebabCase(word) {
return word.replace(/[A-Z]+(?![a-z])|[A-Z]/g, ($, ofs) => (ofs ? "-" : "") + $.toLowerCase());
}
/**
* Convert kebab case to camel case
* @function
* @param {string} word - The word needed to be converted from kebab case to camel case
* @returns {string} - The word returned as camel case
*/
function convertKebabToCamelCase(word) {
return word
.split("-")
.map((token) => (0, exports.capitalizeText)(token))
.join("");
}
/**
* Generate acronym from text
* @param term term to be converted to an acronym
* @returns an acronym generated from the term
*/
function generateAcronym(term) {
return term
.split(" ")
.map((word) => word[0])
.join("");
}
/**
* Validate if a word is acronym
* @function
* @param {string} word - The word that is being validated as acronym
* @returns {string} - The boolean value when the condition is met
*/
function isAcronym(word) {
return word.toUpperCase() === word;
}
/**
* Convert acronym to kebab case
* @function
* @param {string} word - The acronym to be converted to kebab case
* @returns {string} - The word returned as camel case
*/
function acronymToKebabCase(word) {
if (!isAcronym(word)) {
throw new Error(`The text passed: ${word} is not an acronym.`);
}
return word
.split("")
.map((token) => token.toLowerCase())
.join("-");
}
/**
* @function
* @param value The string to be displayed
* @returns The passed string or the default string if the passed string is null or undefined
*/
const handleNullDisplay = (value, defaultValue = "N/A") => value !== null && value !== void 0 ? value : defaultValue;
exports.handleNullDisplay = handleNullDisplay;
/**
* @function
* @param text The string to be capitalized
* @returns The string in a capitalized form
*/
const capitalizeText = (text) => {
if (!text)
return "";
return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
};
exports.capitalizeText = capitalizeText;
/**
* Enforces a character limit on a given string.
* @function
* @param {object} options - The options for the function.
* @param {string} options.text - The text to limit.
* @param {number} options.characterLimit - The maximum number of characters allowed.
* @param {function} options.onCharacterLimit - The function to call when the character limit is exceeded.
* @returns {string} The original string if it is shorter than the character limit, or a truncated version of the string if it is longer.
*/
const enforceCharacterLimit = ({ text, characterLimit, onCharacterLimit, }) => {
if (text.length > characterLimit) {
onCharacterLimit();
return text.slice(0, characterLimit);
}
return text;
};
exports.enforceCharacterLimit = enforceCharacterLimit;
/**
* Validate email if its a proper email or not
* @function
* @param email The email to be validated
* @returns The boolean value when the condition is met
*/
const isValidEmail = (email) => {
// First check for null/undefined
if (!email) {
return false;
}
// Check if the email has an @ symbol and the length of the email tokens is exactly 2
const parts = email.split("@");
if (parts.length !== 2) {
return false;
}
const [local, domain] = parts;
// Check local part rules
if (!local || local.length === 0) {
return false;
}
if (local.startsWith(".") || local.endsWith(".")) {
return false;
}
if (local.includes("..")) {
return false;
}
if (!/^[a-zA-Z0-9][a-zA-Z0-9._+-]*$/.test(local)) {
return false;
}
// Check domain part rules
const domainRegex = /^[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}$/;
return domainRegex.test(domain);
};
exports.isValidEmail = isValidEmail;
/**
* Generate ID from word
* @function
* @param word The word needed to generate ID from
* @returns The generated ID from the word
*/
function generateIDFromWord(text) {
return text
.split(" ")
.map((word) => word.toLowerCase())
.join("-");
}
/**
* Get the word from the generated ID
* @function
* @param id The id that is needed to get the word from.
* @param customList The word lists that are used to check the original words from.
* @returns The word that is got from the id
*/
function generateWordFromId(id, customList = {}) {
var _a;
return (_a = customList[id]) !== null && _a !== void 0 ? _a : id.split("-").map(exports.capitalizeText).join(" ");
}
/**
* Get the slug from words
* @function
* @param id The id that will be in the slug
* @param words The words that will be in the slug
* @returns The slug from the words and it will be url path safe
*/
function generateSlugFromWordsWithID(id, ...words) {
let allWords = [...words.map((word) => word.split(" ")).flat(), ...id.split(" ").flat()];
allWords = allWords.map((word) => encodeURIComponent(word.toLocaleLowerCase()));
return allWords.join("-");
}
/**
* Extracts the id from the slug
* @function
* @param slug The slug associated with the id
* @returns The id from the slug
*/
function extractIDfromSlug(slug) {
if (!slug) {
throw new Error("slug cannot be empty, null or undefined string");
}
return slug.split("-").pop();
}
/**
* Abbreviate number
* @function
* @param number The number to be abbreviated
* @returns The string representation of the abbreviated number
*/
const abbreviateNumber = (number) => {
const abbreviations = [
{ value: 1e9, symbol: "B" },
{ value: 1e6, symbol: "M" },
{ value: 1e3, symbol: "K" },
];
if (number === null || number === undefined || isNaN(number))
return null;
const abbreviated = abbreviations.find(({ value }) => Math.abs(number) >= value);
if (abbreviated) {
const { value, symbol } = abbreviated;
return (number / value).toFixed(2).replace(/\.00$/, "") + symbol;
}
return number.toString();
};
exports.abbreviateNumber = abbreviateNumber;