Skip to content

Files

Latest commit

author
juanantonioledesma
Mar 24, 2023
44595c8 · Mar 24, 2023

History

History
42 lines (30 loc) · 1.33 KB

convert-string-to-camel-case.md

File metadata and controls

42 lines (30 loc) · 1.33 KB

Convert string to camel case 6 Kyu

LINK TO THE KATA - REGULAR EXPRESSIONS ALGORITHMS STRINGS

Description

Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case). The next words should be always capitalized.

Examples

"the-stealth-warrior" gets converted to "theStealthWarrior"

"The_Stealth_Warrior" gets converted to "TheStealthWarrior"

"The_Stealth-Warrior" gets converted to "TheStealthWarrior"

Solution

const getSplitSentence = (sentence, divider) => sentence.split(divider)

const capitalizeFirstLetter = string => {
  return string.charAt(0).toUpperCase() + string.slice(1)
}

const toCamelCase = string => {
  const splitSentence = string.includes('-')
    ? getSplitSentence(string, '-')
    : getSplitSentence(string, '_')

  return splitSentence
    .map((word, index) => {
      if (index === 0) return word
      return capitalizeFirstLetter(word)
    })
    .join('')
}