0% found this document useful (0 votes)
12 views

Case Conversion Function

Uploaded by

Elliot Lassey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Case Conversion Function

Uploaded by

Elliot Lassey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Case Conversion Function

In this kata, you will make a function that converts between camelCase, snake_case, and kebab-
case.

You must write a function that changes to a given case. It must be able to handle all three case
types:

py> change_case("snakeCase", "snake")


"snake_case"
py> change_case("some-lisp-name", "camel")
"someLispName"
py> change_case("map_to_all", "kebab")
"map-to-all"
py> change_case("doHTMLRequest", "kebab")
"do-h-t-m-l-request"
py> change_case("invalid-inPut_bad", "kebab")
None
py> change_case("valid-input", "huh???")
None
py> change_case("", "camel")
""
Your function must deal with invalid input as shown, though it will only be passed strings.
Furthermore, all valid identifiers will be lowercase except when necessary, in other words on word
boundaries in camelCase.

(Any translations would be greatly appreciated!)

To tackle this problem, we need to identify the case type of the input string and then convert it to the
requested case (`camel`, `snake`, or `kebab`). We'll also handle invalid cases by returning `None`.

Here's a step-by-step approach:

1. Identify Case Type: Determine if the input string is in `camelCase`, `snake_case`, or `kebab-case`.
`camelCase`:Has no underscores or hyphens, and some letters are uppercase.
`snake_case`: Has only lowercase letters and underscores (`_`).
`kebab-case`: Has only lowercase letters and hyphens (`-`).

2. Convert to Desired Case:


To convert to `camelCase`, capitalize each word except the first and remove separators.
To convert to `snake_case`, convert to lowercase and join words with underscores.
To convert to `kebab-case`, convert to lowercase and join words with hyphens.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/4
3. Invalid Cases:
If the input contains both underscores and hyphens, it's considered invalid.
If the input case type does not match any of the three expected types, return `None`.
If the target case is invalid, return `None`.

4. Empty String: Return an empty string if the input is empty.

Here’s the Python code implementing the solution:

python

import re

def change_case(identifier, target_case):


# Check for empty string
if identifier == "":
return ""

# Check for invalid input: both hyphens and underscores


if '-' in identifier and '_' in identifier:
return None

# Determine the original case type


if '-' in identifier:
# It's kebab-case
words = identifier.split('-')
elif '_' in identifier:
# It's snake_case
words = identifier.split('_')
elif identifier[0].islower() and any(c.isupper() for c in identifier):
# It's camelCase
words = re.findall(r'[a-z]+|[A-Z][a-z]*', identifier)
words = [w.lower() for w in words] # Normalize all words to lowercase
else:
# Invalid case type
return None

# Convert to the target case


if target_case == "snake":
return "_".join(words)
elif target_case == "kebab":
return "-".join(words)
elif target_case == "camel":
return words[0] + "".join(word.capitalize() for word in words[1:])
else:
# Invalid target case
return None

# Test cases
print(change_case("snakeCase", "snake")) # "snake_case"
print(change_case("some-lisp-name", "camel")) # "someLispName"
print(change_case("map_to_all", "kebab")) # "map-to-all"
print(change_case("doHTMLRequest", "kebab")) # "do-h-t-m-l-request"
print(change_case("invalid-inPut_bad", "kebab")) # None
print(change_case("valid-input", "huh???")) # None
print(change_case("", "camel")) # ""

Explanation:

Regex `re.findall(r'[a-z]+|[A-Z][a-z]*', identifier)`: This matches sequences of lowercase


letters or uppercase letters followed by lowercase letters, which helps split `camelCase` into
individual words.
Conversion Logic:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/4
For `snake_case`, we join words with `_`.
For `kebab-case`, we join words with `-`.
For `camelCase`, we capitalize all words except the first, then join them.

This solution ensures correct conversions and handles invalid inputs gracefully.

snakeCamel_case is invalid: 'snakeCamel_case' should equal None


kebabCamel-case is invalid: 'kebabCamel_case' should equal None
case-Camel is invalid: 'case-Camel' should equal None

You're correct; the solution needs to account for inputs where `camelCase`-style uppercase letters are
mixed with `snake_case` or `kebab-case`. If there’s any mixture of `camelCase` capitalization with
underscores or hyphens, we should return `None`. Let’s update the function to include this validation.

Here’s the revised code:

python

import re

def change_case(identifier, target_case):


# Check for empty string
if identifier == "":
return ""

# Check for invalid input: both hyphens and underscores, or uppercase letters with und
erscores/hyphens
if '-' in identifier and '_' in identifier:
return None
if any(c.isupper() for c in identifier) and ('_' in identifier or '-' in identifier):
return None

# Determine the original case type


if '-' in identifier:
# It's kebab-case
words = identifier.split('-')
elif '_' in identifier:
# It's snake_case
words = identifier.split('_')
elif identifier[0].islower() and any(c.isupper() for c in identifier):
# It's camelCase
words = re.findall(r'[a-z]+|[A-Z][a-z]*', identifier)
words = [w.lower() for w in words] # Normalize all words to lowercase
else:
# Invalid case type
return None

# Convert to the target case


if target_case == "snake":
return "_".join(words)
elif target_case == "kebab":
return "-".join(words)
elif target_case == "camel":
return words[0] + "".join(word.capitalize() for word in words[1:])
else:
# Invalid target case
return None

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 3/4
# Test cases
print(change_case("snakeCase", "snake")) # "snake_case"
print(change_case("some-lisp-name", "camel")) # "someLispName"
print(change_case("map_to_all", "kebab")) # "map-to-all"
print(change_case("doHTMLRequest", "kebab")) # "do-h-t-m-l-request"
print(change_case("invalid-inPut_bad", "kebab")) # None
print(change_case("valid-input", "huh???")) # None
print(change_case("", "camel")) # ""
print(change_case("snakeCamel_case", "kebab")) # None
print(change_case("kebabCamel-case", "snake")) # None
print(change_case("case-Camel", "camel")) # None

Explanation of Changes:

New Validation: The condition `if any(c.isupper() for c in identifier) and ('_' in
identifier or '-' in identifier)` checks if there’s any uppercase letter together with either `_`
or `-`, marking it as invalid.

This ensures mixed-case strings with separators are caught and handled as invalid.
ChatGPT can make mistakes. Check important info.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 4/4

You might also like