코드스테이츠 42기/[TIL] Section 3
S3U1 [자료구조/알고리즘] 재귀 2
by 랜덤다이스
2022. 12. 16.
1. 문제 풀이 stringifyJSON
function stringifyJSON(obj) {
if (obj === null) {
return "null";
}
if (typeof obj === "number" || typeof obj === "boolean") {
return String(obj);
}
if (typeof obj === "string") {
return `"${obj}"`;
}
//obj가 배열인 경우
if (Array.isArray(obj)) {
const result = [];
obj.forEach(function (element) {
result.push(stringifyJSON(element))
})
return `[${result}]`;
}
//obj가 객체인 경우 (객체에는 배열, 객체 모두 포함되지만 배열인 경우보다 아래에 작성했으므로 배열은 제외된다.)
if (typeof obj === "object") {
let result = "";
for (let key in obj) {
if (obj[key] === undefined || typeof obj[key] === "function") {
result = String(result);
} else {
result = result + `${stringifyJSON(key)}:${stringifyJSON(obj[key])},`;
}
}
result = result.substr(0, result.length - 1);
return `{${result}}`;
}
};
// 다음 코드는 결과 제출을 위한 코드입니다. 신경 쓰지 않아도 좋습니다.
if (typeof window === "undefined") {
module.exports = stringifyJSON;
}
2. 문제 풀이 Tree-UI
// TODO: createTreeView 함수를 재귀(자기 자신을 계속 부르게 함)호출하여 테스트케이스를 통과하세요.
// GOAL: 최종 결과가 resut.html와 같은 모습으로 나와야 합니다.
const root = document.getElementById('root');
// imperitive solution
function createTreeView(menu, currentNode) {
for (let i = 0; i < menu.length; i++) {
const li = document.createElement('li');
if (menu[i].children) {
const input = document.createElement('input');
input.type = 'checkbox';
const span = document.createElement('span');
span.textContent = menu[i].name;
const ul = document.createElement('ul');
li.append(input, span, ul);
currentNode.append(li);
createTreeView(menu[i].children, ul);
} else {
li.textContent = menu[i].name;
currentNode.append(li);
}
}
}
// declarative solution
// function createTreeView(menu, currentNode) {
// const appendCollectionsInfo = function (currentNode, collections) {
// const li = document.createElement('li');
// const checkbox = document.createElement('input');
// checkbox.type = 'checkbox';
// const isItem = collections.type === 'item' ? true : false;
// if (isItem) {
// li.append(collections.name);
// } else {
// const groupName = document.createElement('span');
// groupName.textContent = collections.name;
// li.append(checkbox, groupName);
// }
// const haveChildren = Boolean(collections.children);
// const children = collections.children;
// if (haveChildren) {
// const ul = document.createElement('ul');
// createTreeView(children, ul);
// li.append(ul);
// }
// currentNode.append(li);
// return currentNode;
// };
// menu.reduce(appendCollectionsInfo, currentNode);
// }
createTreeView(menu, root);