알고리즘/프로그래머스 - JS

[프로그래머스-JS] level.1 신규아이디 추천

개발자성장기 2022. 6. 11. 03:47
반응형

https://programmers.co.kr/learn/courses/30/lessons/72410

 

코딩테스트 연습 - 신규 아이디 추천

카카오에 입사한 신입 개발자 네오는 "카카오계정개발팀"에 배치되어, 카카오 서비스에 가입하는 유저들의 아이디를 생성하는 업무를 담당하게 되었습니다. "네오"에게 주어진 첫 업무는 새로

programmers.co.kr

 

 

나의코드

딱 보자마자 이건 일일이 확인하는게아닌 정규 표현식으로 해야한다는 게 감이와서 

정석책 펴서 다시 공부했음

 

그 결과

 

function solution(new_id) {
    var answer = '';
    
    //1단계  (소문자 대문자 바꾸기 복습 <배열이 아닌데도 가능>)
    let result = new_id.toLowerCase()
    
    //2단계
    const reg = /[^\w\sㄱ-힣\-.]/g;
    result = result.replace(reg, ``)
    
    //3단계
    const kaka = /\.{2,}/g
    result = result.replace(kaka, `.`)
    
    //4단계    
    const fofo = /^\.|\.$/g
    result = result.replace(fofo, ``)
    
    //5단계   
    if(result === ""){
        result = "a"
    }
    
    //6단계
    if(result.length >= 16){
        result = result.slice(0,15)
        const wowo = /\.$/g
        result= result.replace(wowo, ``)
    }
    
    // 7단계 
    if(result.length <= 2){
        
        result = result.split("")
        const yoyo = result[result.length - 1]
        result = result.join("")
        
        if(result.length === 1){
            result = result + yoyo.repeat(2)
        }else{
            result = result + yoyo
        }
        
    } 
    return result;
}

굉장히 길어졌다 

특히 5단계와 6단계는 7단계는 정말 별로인 것 같다 

다 풀고 다른 사람들이 푼 것을 봤는데 wow 깜짝 놀랐다. 

정말 간단히 푸셨고 체이닝을 잘 하셨다. 

 

 

 

다른분이 푼 것 (1)

function solution(new_id) {
    const answer = new_id
        .toLowerCase() // 1
        .replace(/[^\w-_.]/g, '') // 2
        .replace(/\.+/g, '.') // 3
        .replace(/^\.|\.$/g, '') // 4
        .replace(/^$/, 'a') // 5
        .slice(0, 15).replace(/\.$/, ''); // 6
    const len = answer.length;
    return len > 2 ? answer : answer + answer.charAt(len - 1).repeat(3 - len);
}

특히 5번째는 기억하자 

/^$/ 이렇게 하면 할당된 값이 없다는 뜻이다. 

 

charAt?? 

 

 

다른분이 푼 것(2)

const solution = (new_id) => {
    const id = new_id
        .toLowerCase()
        .replace(/[^\w\d-_.]/g, '')
        .replace(/\.{2,}/g, '.')
        .replace(/^\.|\.$/g, '')
        .padEnd(1, 'a')
        .slice(0, 15)
        .replace(/^\.|\.$/g, '')        
    return id.padEnd(3, id[id.length-1])
}

 

padEnd()  이것은 처음 보는 함수라서 신선했다. 

 

관련개념 

https://html-jc.tistory.com/302

 

[JS-개념] padEnd()

string.prototype.padEnd() padEnd() 메서드는 현재 문자열에 다른 문자열을 채워, 주어진 길이를 만족하는 새로운 문자열을 반환한다 채워넣기는 대상 문자열의 끝(우측)부터 적용됩니다. const str1 = 'Breade

html-jc.tistory.com

 

반응형