Last active
November 9, 2021 17:09
-
-
Save kimagure44/940a0bfca1dedbead671c915a41a572a to your computer and use it in GitHub Desktop.
Convierte un texto a un tipo de variable (CamelCaseUpper, camelCaseLower, kebab-case y snake_case)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const convert = ([...str], type) => { | |
try { | |
const t = ['camelUp', 'camelLo', 'kebab', 'snake']; | |
if (!type || !t.includes(type)) { | |
throw `El argumento "type" es obligatorio y debe contener uno de los siguientes tipos: ${t.join(', ')}`; | |
} | |
const symbol = { | |
snake: '_', | |
kebab: '-', | |
camelUp: 'toUpperCase', | |
camelLo: 'toLowerCase' | |
}; | |
const u = str => str.toUpperCase(); | |
return str.map((lt, ix) => { | |
const iC = [t[0], t[1]].includes(type); | |
const iS = [t[2], t[3]].includes(type); | |
const sy = symbol[type]; | |
return lt === u(lt) ? ix === 0 && iC ? lt[sy]() : `${ix > 0 && iS ? sy : ''}${lt}` : lt; | |
}).join(''); | |
} catch(err) { | |
throw new Error(err); | |
} | |
}; | |
console.log(convert('VariableQueNecesito', 'camelUp')); // VariableQueNecesito | |
console.log(convert('VariableQueNecesito', 'camelLo')); // variableQueNecesito | |
console.log(convert('VariableQueNecesito', 'snake')); // Variable_Que_Necesito | |
console.log(convert('VariableQueNecesito', 'kebab')); // Variable-Que-Necesito | |
console.log(convert('variableQueNecesito', 'snake')); // variable_Que_Necesito | |
console.log(convert('variableQueNecesito', 'kebab')); // variable-Que-Necesito | |
console.log(convert('variableQueNecesito', '')); // error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment