UNPKG

ts-case-transformer

Version:

A TypeScript utility for transforming object keys between different case styles with full type safety

88 lines (87 loc) 2.56 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.transformKeys = transformKeys; function toCamelCase(str) { return str .replace(/[-_](\w)/g, (_, c) => c.toUpperCase()) .replace(/^[A-Z]/, (c) => c.toLowerCase()); } function toSnakeCase(str) { return str .replace(/([A-Z])/g, "_$1") .replace(/[-]/g, "_") .replace(/^_/, "") .toLowerCase(); } function toKebabCase(str) { return str .replace(/([A-Z])/g, "-$1") .replace(/[_]/g, "-") .replace(/^-/, "") .toLowerCase(); } function toPascalCase(str) { return str .split(/[-_]/) .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) .join(""); } function toFlatCase(str) { return str .replace(/[-_\s]+/g, '') .replace(/([A-Z])/g, (m) => m.toLowerCase()); } function toUpperFlatCase(str) { return str .replace(/[-_\s]+/g, '') .toUpperCase(); } function toPascalSnakeCase(str) { return str .split(/[-_\s]+/) .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) .join('_'); } function toCamelSnakeCase(str) { const words = str.split(/[-_\s]+/); return [ words[0].toLowerCase(), ...words.slice(1).map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) ].join('_'); } function toScreamingSnakeCase(str) { return str .replace(/([A-Z])/g, '_$1') .replace(/[-\s]+/g, '_') .replace(/^_/, '') .toUpperCase(); } const transformers = { camelCase: toCamelCase, snake_case: toSnakeCase, 'kebab-case': toKebabCase, PascalCase: toPascalCase, flatcase: toFlatCase, UPPERFLATCASE: toUpperFlatCase, Pascal_Snake_Case: toPascalSnakeCase, camel_Snake_Case: toCamelSnakeCase, SCREAMING_SNAKE_CASE: toScreamingSnakeCase, }; function transformKeys(obj, caseType = "camelCase") { if (Array.isArray(obj)) { return obj.map((item) => typeof item === "object" && item !== null ? transformKeys(item, caseType) : item); } const transformer = transformers[caseType]; return Object.entries(obj).reduce((acc, [key, value]) => { const transformedKey = transformer(key); const transformedValue = value && typeof value === "object" ? transformKeys(value, caseType) : value; return { ...acc, [transformedKey]: transformedValue, }; }, {}); }