6kyu
Write a function that takes in a string of one or more words, and returns the same string, but with all words that have five or more letters reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present.
Examples:
"Hey fellow warriors" --> "Hey wollef sroirraw"
"This is a test --> "This is a test"
"This is another test" --> "This is rehtona test"
function spinWords(string){
//1. 공백이 포함되어있는지 판단 (o면 문장 그외 단어)
if(string.includes(" ") === true)
{
let rev = [];
let rev2 = [];
//1.1 공백 포함된 경우 === 문장
let junk = string.split(" ");
for(let i = 0; i<junk.length; i++){
if(junk[i].length >= 5){
let revw = junk[i].split('');
for(let j = revw.length-1 ; j >= 0 ; j--){
rev.push(revw[j]);
if(j === 0){
rev2.push(rev.join(""));
rev = [];
}
}
}else{
rev2.push(junk[i]);
}
}
let result = rev2.join(" ");
return result;
}
else
{
//1.2 공백 미포함 경우 === 단어
if(string.length >= 5){
let newword = "";
let revword = string.split("");
let proc = [];
for(j=revword.length-1 ; j>=0;j--){
proc.push(revword[j]);
if(j === 0) {
newword = proc.join('');
}
}
return newword;
}else{
return string;
}
// 단어의 갯수 판단 => 5글자 이상 역순 , 그외 그대로 반환
}
}
function spinWords(words){
return words.split(' ').map(function (word) {
return (word.length > 4) ? word.split('').reverse().join('') : word;
}).join(' ');
}
너무 비효율적으로 로직을 길게 작성했다. 그리고 변수들을 너무 많이 선언함..
그리고 join을 사용하면 배열이 아니라 어차피 문자열이 반환되는데 문장과 단어를 나눌 필요가 없었다.
map을 제대로 이해하고있지 않은듯.. map은 이어서 배열로 반환되는 것!
메소드 map이 있다는 건 알지만, 그걸 실제로 코드로 적용해보는 연습이 매우매우 많이 필요하다.
그리고 시간이 조금 걸리더라도, 활용되는 예제를 보고 코드를 직접 쳐보면서 차근차근 익혀나가는 것이 중요한 것같다. 그리고 개념하나를 익히면 비슷한 문제들을 풀어서 잘 익히기!!!