[05.04.22] Coding test

Juyeon.it·2022년 5월 3일
0

Coding test

목록 보기
23/32

WeIrD StRiNg CaSe

Description

Write a function toWeirdCase (weirdcase in Ruby) that accepts a string, and returns the same string with all even indexed characters in each word upper cased, and all odd indexed characters in each word lower cased. The indexing just explained is zero based, so the zero-ith index is even, therefore that character should be upper cased and you need to start over for each word.
The passed in string will only consist of alphabetical characters and spaces(' '). Spaces will only be present if there are multiple words. Words will be separated by a single space(' ').
Examples:
toWeirdCase( "String" );//=> returns "StRiNg"
toWeirdCase( "Weird string case" );//=> returns "WeIrD StRiNg CaSe"

My answer

function toWeirdCase(string){
  let result = string.split(' ').map(function(word) {
    let arr = word.split('');
    for(let i = 0; i < arr.length; i++) {
      i % 2 === 0 ? arr[i] = arr[i].toUpperCase() : arr[i] = arr[i].toLowerCase();
    }
    return arr.join('');
  })
  
  return result.join(' ');
}

Other solutions

function toWeirdCase(string){
  return string.split(' ').map(function(word){
    return word.split('').map(function(letter, index){
      return index % 2 == 0 ? letter.toUpperCase() : letter.toLowerCase()
    }).join('');
  }).join(' ');
}

0개의 댓글

관련 채용 정보