본문 바로가기
알고리즘/Codewars

[Codewars] altERnaTIng cAsE <=> ALTerNAtiNG CaSe (8 kyu) / JavaScript

by fluss 2023. 5. 7.

https://www.codewars.com/kata/56efc695740d30f963000557

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

altERnaTIng cAsE <=> ALTerNAtiNG CaSe

Define String.prototype.toAlternatingCase (or a similar function/method such as to_alternating_case/toAlternatingCase/ToAlternatingCase in your selected language; see the initial solution for details) such that each lowercase letter becomes uppercase and each uppercase letter becomes lowercase. For example:

"hello world".toAlternatingCase() === "HELLO WORLD"
"HELLO WORLD".toAlternatingCase() === "hello world"
"hello WORLD".toAlternatingCase() === "HELLO world"
"HeLLo WoRLD".toAlternatingCase() === "hEllO wOrld"
"12345".toAlternatingCase()       === "12345"                   // Non-alphabetical characters are unaffected
"1a2b3c4d5e".toAlternatingCase()  === "1A2B3C4D5E"
"String.prototype.toAlternatingCase".toAlternatingCase() === "sTRING.PROTOTYPE.TOaLTERNATINGcASE"

As usual, your function/method should be pure, i.e. it should not mutate the original string.

 

코드

String.prototype.toAlternatingCase = function () {
  let str = "";
  for(let i = 0; i < this.length; i++){
    const el = this[i];
    str += el === el.toUpperCase() ? el.toLowerCase() : el.toUpperCase();
  }
  return str;
}

댓글