toCamelCase.js

Codewars 알고리즘 풀이


Problem

  • Complete the function so that it converts dash/underscore delimited words into camel casing.
    • dash/underscore로 구분된 단어를 CamelCase(낙타 대문자)로 변환한다.
  • 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).
    • 첫 번째 단어가 대문자인 경우에만 첫 단어를 대문자로 표기한다.



Solution 01

function toCamelCase(str) {
  let result = '';
  
  for (let i = 0; i < str.length; i++) {
    if (str[i] === '-' || str[i] === '_') {
      result += str[i + 1].toUpperCase();
      i++;
    } else {
      result += str[i];
    }
  }
  return result;
}

toCamelCase('');               // ''
toCamelCase('user-id');        // userId
toCamelCase('user_password');  // userPassword
toCamelCase('Not-A-Robot');    // NotARobot


Solution 02

function toCamelCase(str) {
  let arr = str.split('');
  
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === '-' || arr[i] === '_') {
      arr.splice(i, 1);
      arr.splice(i, 1, arr[i].toUpperCase());
    }
  }
  return arr.toString().split(',').join('');
}

toCamelCase('');               // ''
toCamelCase('user-id');        // userId
toCamelCase('user_password');  // userPassword
toCamelCase('Not-A-Robot');    // NotARobot


Solution 03

function toCamelCase(str) {
  let arr = str.split(/[-_]/);
  
  for (let i = 1; i < arr.length; i++) {
    arr[i] = arr[i][0].toUpperCase() + arr[i].slice(1);
  }
  return arr.join('');
}

toCamelCase('');               // ''
toCamelCase('user-id');        // userId
toCamelCase('user_password');  // userPassword
toCamelCase('Not-A-Robot');    // NotARobot


Solution 04

function toCamelCase(str) {
  return str.replace(/[-_]\w/g, i => i[1].toUpperCase());
}

toCamelCase('');               // ''
toCamelCase('user-id');        // userId
toCamelCase('user_password');  // userPassword
toCamelCase('Not-A-Robot');    // NotARobot


Solution 05

function toCamelCase(str) {
  return str.replace(/[-_](.)/g, i => i[1].toUpperCase());
}

toCamelCase('');               // ''
toCamelCase('user-id');        // userId
toCamelCase('user_password');  // userPassword
toCamelCase('Not-A-Robot');    // NotARobot