spec/stringifyJSONSpec.js의 stringifiableObjects 배열을 참고해서 테스트에서 어떤 input 값들이주어지고, 어떻게 stringify해 주어야 할지 생각해 보세요.
그냥 테스트 통과를 하고 싶으시다면, 다음과 같이 구현하면 될 거예요.
const stringifyJSON = JSON.stringify;
stringfyJSON 함수는 객체를 문자열로 바꿔서 전송하기 위해 직렬화 하는 함수를 만드는 것이다.
(1) typeof 메서드를 통해서 input값의 종류를 구별해 결과값을 구해야 합니다.
(2) 문자 boolean 숫자 배열 객체일때 그 와중에 배열 객체일때 재귀함수를 통해 안에 또 배열이 있거나 객체가 있을때 문자열로 만들어주어야 합니다.
✓ 객체는 문자열 "9"로 변환되어야 합니다
if (typeof obj === "number"){
return String(obj);
}
✓ 객체는 문자열 "null"로 변환되어야 합니다
if(obj === null){
return "null";
}
typeof obj === 'null'하면 안되는 이유: 객체로 잡힌다.
✓ 객체는 문자열 "true"로 변환되어야 합니다
✓ 객체는 문자열 "false"로 변환되어야 합니다
if(typeof obj === "boolean"){
return String(obj);
}
✓ 객체는 문자열 ""Hello world""로 변환되어야 합니다
if(typeof obj === "string"){
return `"${obj}"`
}
✓ 객체는 문자열 "[]"로 변환되어야 합니다
✓ 객체는 문자열 "[8]"로 변환되어야 합니다
✓ 객체는 문자열 "["hi"]"로 변환되어야 합니다
✓ 객체는 문자열 "[8,"hi"]"로 변환되어야 합니다
✓ 객체는 문자열 "[1,0,-1,-0.3,0.3,1343.32,3345,0.00011999]"로 변환되어야 합니다
✓ 객체는 문자열 "[8,[[],3,4]]"로 변환되어야 합니다
✓ 객체는 문자열 "[[[["foo"]]]]"로 변환되어야 합니다
if(Array.isArray(obj)){
let newArr = [];
obj.forEach(function (ele){
newArr.push(stringifyJSON(ele))
})
return `[${newArr}]`
}
forEach 메서드 링크
-> 메서드를 통해서 배열 안에 있는 요소 하나 하나를 끌어낸다.
-> push 메서드와 stringifyJSON 재귀함수를 통해서 빈배열에 새롭게 삽입한다.
Banana 스러운 템플릿 리터널
[${}]
let newArr2 = [1, 3, 4]
undefined
let a = '9'
undefined
newArr2.push(a)
4
newArr2
(4) [1, 3, 4, '9']
// 여기서 템플릿 리터널을 쓰면 안에는 숫자와 문자열로 바뀐다.
`[${newArr2}]`
'[1,3,4,9]'
새로운 방법
✓ 객체는 문자열 "{}"로 변환되어야 합니다
✓ 객체는 문자열 "{"a":"apple"}"로 변환되어야 합니다
✓ 객체는 문자열 "{"foo":true,"bar":false,"baz":null}"로 변환되어야 합니다
✓ 객체는 문자열 "{"boolean, true":true,"boolean, false":false,"null":null}"로 변환되어야 합니다
✓ 객체는 문자열 "{"a":{"b":"c"}}"로 변환되어야 합니다
✓ 객체는 문자열 "{"a":["b","c"]}"로 변환되어야 합니다
✓ 객체는 문자열 "[{"a":"b"},{"c":"d"}]"로 변환되어야 합니다
✓ 객체는 문자열 "{"a":[],"c":{},"b":true}"로 변환되어야 합니다
✓ 함수와 undefined는 stringify되지 않습니다.
if(typeof obj === "object"){
let result = "";
for(let key in obj) {
if(obj[key] === undefined || typeof obj[key] === "function"){
result = String(result);
} else {
result += `${stringifyJSON(key)}:${stringifyJSON(obj[key])},`;
}
}
result = result.substr(0, result.length -1);
return `{${result}}`
}
object(객체)를 문자화로 바로 하면 object Object 이런식으로 나온다.
function stringifyJSON(obj) {
if(obj === null){
return "null";
}
if (typeof obj === "number"){
return String(obj);
}
if(typeof obj === "boolean"){
return String(obj);
}
if(typeof obj === "string"){
return `"${obj}"`
}
if(Array.isArray(obj)){
let newArr = [];
obj.forEach(function (ele){
newArr.push(stringifyJSON(ele))
})
return `[${newArr}]`
}
if(typeof obj === "object"){
let result = "";
for(let key in obj) {
if(obj[key] === undefined || typeof obj[key] === "function"){
result = String(result);
} else {
result += `${stringifyJSON(key)}:${stringifyJSON(obj[key])},`;
}
}
result = result.substr(0, result.length -1);
return `{${result}}`
}
// your code goes here
};
출처 : 코드스테이츠