Skip to content

Instantly share code, notes, and snippets.

@igoratron
Created April 20, 2018 13:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igoratron/4c265ac08049041966cd4a121cfb8e1b to your computer and use it in GitHub Desktop.
Save igoratron/4c265ac08049041966cd4a121cfb8e1b to your computer and use it in GitHub Desktop.
Change case kata
function changeCase(identifier, targetCase){
if(!isSupportedCase(targetCase)) {
return;
}
if(!isValid(identifier)) {
return;
}
const words = tokenise(identifier);
return format(targetCase, words);
}
function isSupportedCase(targetCase) {
const supportedCases = ['camel', 'snake', 'kebab'];
return supportedCases.includes(targetCase);
}
function isValid(identifier) {
const camelSeparator = /[A-Z]/;
const kebabSeparator = /_/;
const snakeSeparator = /-/;
const separators = [camelSeparator, kebabSeparator, snakeSeparator]
.map(check => check.test(identifier))
.filter(v => v)
.length;
return separators <= 1;
}
function tokenise(identifier) {
return identifier
.split(/-|_|(?=[A-Z])/)
.map(a => a.toLowerCase());
}
function format(targetCase, words) {
switch(targetCase) {
case "kebab":
return words.join('-');
case "snake":
return words.join('_');
case "camel":
const [first, ...rest] = words;
return [first, ...rest.map(capitalise)].join('');
}
}
function capitalise(word) {
return word.replace(/./, letter => letter.toUpperCase());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment