Created
April 20, 2018 13:42
-
-
Save igoratron/4c265ac08049041966cd4a121cfb8e1b to your computer and use it in GitHub Desktop.
Change case kata
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
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