nhb-toolbox
Version:
A versatile collection of smart, efficient, and reusable utility functions and classes for everyday development needs.
111 lines (110 loc) • 4.3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateRandomID = exports.truncateString = void 0;
exports.capitalizeString = capitalizeString;
exports.trimString = trimString;
/**
* * Utility to convert the first letter of any string to uppercase and the rest lowercase (unless specified).
* * Handles surrounding symbols like quotes or parentheses.
*
* @param string String to be capitalized.
* @param options Options to customize the capitalization.
* @returns Capitalized string or fully uppercased string depending on `capitalizeAll` option.
*/
function capitalizeString(string, options) {
if (typeof string !== 'string' || !string)
return '';
const trimmedString = string.trim();
if (!trimmedString)
return '';
const { capitalizeAll = false, capitalizeEachFirst = false, lowerCaseRest = true, } = options || {};
if (capitalizeAll) {
return trimmedString.toUpperCase();
}
if (capitalizeEachFirst) {
return trimmedString
?.split(/\s+/)
?.map((word) => capitalizeString(word, { lowerCaseRest }))
?.join(' ');
}
const matchArray = trimmedString.match(/^(\W*)(\w)(.*)$/);
if (matchArray && matchArray?.length === 4) {
const [_, leadingSymbols, firstLetter, rest] = matchArray;
return leadingSymbols
.concat(firstLetter.toUpperCase())
.concat(lowerCaseRest ? rest.toLowerCase() : rest);
}
return trimmedString
.charAt(0)
.toUpperCase()
.concat(lowerCaseRest ?
trimmedString.slice(1).toLowerCase()
: trimmedString.slice(1));
}
/**
* * Utility to truncate a string to a specified length.
*
* @param string The string to truncate.
* @param maxLength The maximum length of the truncated string.
* @returns Truncated string with ellipsis (`...`) (only if it has more length than `maxLength`).
*/
const truncateString = (string, maxLength) => {
if (typeof string !== 'string' || !string)
return '';
const trimmedString = string?.trim();
if (!trimmedString)
return '';
if (trimmedString?.length <= maxLength)
return trimmedString;
return trimmedString?.slice(0, maxLength)?.concat('...');
};
exports.truncateString = truncateString;
/**
* * Generates a random alphanumeric (16 characters long, this length is customizable in the options) ID string composed of an optional `prefix`, `suffix`, a `timestamp`, `caseOption` and a customizable `separator`.
*
* @param options Configuration options for random ID generation.
* @returns The generated ID string composed of the random alphanumeric string of specified length with optional `timeStamp`, `prefix`, and `suffix`, `caseOption` and `separator`.
*/
const generateRandomID = (options) => {
const { prefix = '', suffix = '', timeStamp = false, length = 16, separator = '', caseOption = null, } = options || {};
// generate timestamp
const date = timeStamp ? Date.now() : '';
// Generate a random string of alphanumeric characters
const randomString = Array.from({ length }, () => Math.random().toString(36).slice(2, 3)).join('');
const ID = [
prefix && prefix.trim(),
date,
randomString,
suffix && suffix.trim(),
]
?.filter(Boolean)
?.join(separator);
switch (caseOption) {
case 'upper':
return ID.toUpperCase();
case 'lower':
return ID.toLowerCase();
default:
return ID;
}
};
exports.generateRandomID = generateRandomID;
/**
* * Trims all the words in a string or an array of strings.
*
* @param input String or array of strings.
* @returns Trimmed string or array of strings.
*/
function trimString(input) {
if (!input)
return '';
// If the input is a string, trim each word
if (typeof input === 'string' && !Array.isArray(input)) {
return input?.trim()?.replace(/\s+/g, ' ');
}
// If the input is an array of strings, trim each string in the array
if (Array.isArray(input)) {
return input?.map((str) => typeof str === 'string' ? str?.trim()?.replace(/\s+/g, ' ') : str);
}
throw new Error('Invalid input type. Expected string or array of strings!');
}