
문제 : Codewars_Convert boolean values to strings 'Yes' or 'No' (8kyu)
Complete the method that takes a boolean value and return a "Yes" string for true, or a "No" string for false.
문제 풀이
function boolToWord( bool ){
let trueOrFalse = !!bool;
return trueOrFalse === true ? "Yes" : "No";
}
- 부정논리연산자(!!)를 이용하면 boolean값을 반환하기 때문에 boolToWord의 인수인 bool의 boolean값을 저장할 trueOrFalse라는 변수를 만들었다.
- 이후 삼항연산자를 이용해서 true일 때는 "Yes"를, false일 때는 "No"를 반환하도록 코드 작성
코드 비교
function boolToWord( bool ){
return bool ? 'Yes':'No';
}
- 나는 boolToWord 인수인 bool값을 boolean 값으로 변환해줘야한다 생각했는데 그럴 필요 없이 바로 bool 값이 true면 "Yes"를, false면 "No"를 반환하는 삼항 연산자를 작성했다.
- 위 코드를 보며 삼항 연산자는 truethy값과 falsy값을 비교하는데, 이게 결국 true와 false 값을 연산하는 과정이기 때문에 굳이 boolean으로 변환하지 않아도 되는구나를 이해할 수 있었다.
let boolToWord = bool => bool ? 'Yes' : 'No';
- 첫 번째 코드보다 더 간결하게 작성된 코드이다. 화살표 함수를 사용해서 function과 return을 생략하여 더 간단한 코드가 작성되었다.
문제 : Codewars_Convert a Number to a String! (8kyu)
We need a function that can transform a number (integer) into a string.
What ways of achieving this do you know?
* Examples (input --> output)
123 --> "123"
999 --> "999"
-100 --> "-100"
문제 풀이
function numberToString(num) {
return num.toString();
}
- 숫자를 문자열으로 변환해주는 toString() 메서드를 사용했다.
코드 비교 - 1
function numberToString(num) {
return String(num);
}
- toString() 메서드와 마찬가지로 숫자를 문자열로 변환해주는 String() 메서드를 사용했다.
💡String() , toString() 차이점은 뭘까?
두 메서드 다 숫자를 문자열로 변환해주는 것은 동일하지만, String()은 null, undefined에 대해서도 잘 동작하는 반면, .toString()은 null, undefined 값을 만나면 에러가 발생한다. 아래 예제 코드로 확인해보자
console.log('**null을 string으로 반환하면?**');
let nullToString = null;
console.log(`String 메서드 반환값 => ${String(nullToString)}`);
console.log(`String 메서드 사용했을 때 데이터타입 => ${typeof String(nullToString)}`);
console.log('-----');
console.log(`toString 메서드 반환값 => ${toString(nullToString)}`);
console.log(`toString 메서드 사용했을 때 데이터타입 => ${typeof toString(nullToString)}`);
console.log(`**undefined를 string으로 반환하면?**`);
let undefinedToString = undefined;
console.log(`String 메서드 반환값 => ${String(undefinedToString)}`);
console.log(`String 메서드 사용했을 때 데이터타입 => ${typeof String(undefinedToString)}`);
console.log(`-----`);
console.log(`toString 메서드 반환값 => ${toString(undefinedToString)}`);
console.log(`toString 메서드 사용했을 때 데이터타입 => ${typeof toString(undefinedToString)}`);

코드 비교 - 2
const numberToString = num => `${num}`;
- Template String (*`${}`)을 이용해서 숫자를 바로 문자열으로 바꾼 코드! 좋다!
'Java Script > 알고리즘 풀이' 카테고리의 다른 글
| [알고리즘] 0821 (0) | 2023.08.21 |
|---|---|
| [알고리즘] 0820 (0) | 2023.08.20 |
| [알고리즘] 0816 (0) | 2023.08.16 |
| [알고리즘] 0815 (0) | 2023.08.15 |
| [알고리즘] 0814 (0) | 2023.08.15 |