@augment-vir/common
Version:
A collection of augments, helpers types, functions, and classes for any JavaScript environment.
83 lines (82 loc) • 2.79 kB
JavaScript
/**
* The different string cases.
*
* @category String
* @category Package : @augment-vir/common
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common)
*/
export var StringCase;
(function (StringCase) {
StringCase["Upper"] = "upper";
StringCase["Lower"] = "lower";
})(StringCase || (StringCase = {}));
/**
* Default options for {@link CasingOptions}.
*
* @category String
* @category Package : @augment-vir/common
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common)
*/
export const defaultCasingOptions = {
firstLetterCase: StringCase.Lower,
};
/**
* Set the first letter of the input to uppercase or lowercase.
*
* @category String
* @category Package : @augment-vir/common
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common)
*/
export function setFirstLetterCasing(input, stringCase) {
if (!input.length) {
return '';
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const firstLetter = input[0];
return ((stringCase === StringCase.Upper
? firstLetter.toUpperCase()
: firstLetter.toLowerCase()) + input.slice(1));
}
/**
* Indicates whether the given string has different lower and upper case variants. (Some strings
* don't, such as all numbers or `'√'`.)
*
* @category String
* @category Package : @augment-vir/common
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common)
*/
export function hasCase(input) {
return input.toLowerCase() !== input.toUpperCase();
}
/**
* Checks if the given string is exclusively of the specific case.
*
* Note that some characters have no casing, such as punctuation (they have no difference between
* upper and lower casings). By default, those letters always return `true` for this function,
* regardless of which `caseType` is provided. To instead return `false` for any such characters,
* pass in an options object and set `rejectNoCaseCharacters` to true.
*
* @category String
* @category Package : @augment-vir/common
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common)
*/
export function isCase(input, caseType, options) {
if (!input && options?.rejectNoCaseCharacters) {
return false;
}
for (const letter of input) {
if (!hasCase(letter)) {
if (options?.rejectNoCaseCharacters) {
return false;
}
else {
continue;
}
}
else if ((caseType === StringCase.Upper && letter !== letter.toUpperCase()) ||
(caseType === StringCase.Lower && letter !== letter.toLowerCase())) {
return false;
}
}
return true;
}