UNPKG

@augment-vir/common

Version:

A collection of augments, helpers types, functions, and classes for any JavaScript environment.

58 lines (57 loc) 2.11 kB
import { mergeDefinedProperties } from '../../object/merge-defined-properties.js'; import { defaultCasingOptions, isCase, setFirstLetterCasing, StringCase, } from './casing.js'; /** * Converts a kebab-case string to CamelCase. * * @category String * @category Package : @augment-vir/common * @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) */ export function kebabCaseToCamelCase(rawKebabCase, casingOptions = {}) { const kebabCase = rawKebabCase.toLowerCase(); if (!kebabCase.length) { return ''; } const camelCase = kebabCase .replace(/^-+/, '') .replace(/-{2,}/g, '-') .replace(/-(?:.|$)/g, (dashMatch) => { const letter = dashMatch[1]; if (letter) { return letter.toUpperCase(); } else { return ''; } }); const options = mergeDefinedProperties(defaultCasingOptions, casingOptions); return setFirstLetterCasing(camelCase, options.firstLetterCase); } /** * Converts a CamelCase string to kebab-case. * * @category String * @category Package : @augment-vir/common * @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) */ export function camelCaseToKebabCase(rawCamelCase) { const kebabCase = rawCamelCase .split('') .reduce((accum, currentLetter, index, originalString) => { const previousLetter = index > 0 ? originalString[index - 1] || '' : ''; const nextLetter = index < originalString.length - 1 ? originalString[index + 1] || '' : ''; const possibleWordBoundary = isCase(previousLetter, StringCase.Lower, { rejectNoCaseCharacters: true }) || isCase(nextLetter, StringCase.Lower, { rejectNoCaseCharacters: true }); if (currentLetter === currentLetter.toLowerCase() || index === 0 || !possibleWordBoundary) { accum += currentLetter; } else { accum += `-${currentLetter.toLowerCase()}`; } return accum; }, '') .toLowerCase(); return kebabCase; }