[SEB_FE_44] 자료구조/알고리즘 - 과제

유영준·2023년 4월 12일
post-thumbnail

오늘 배운 주제


  • JSON

오늘 배운 내용


  • JSON

JSON은 JavaScript Object Notation의 줄임말로, 데이터 교환을 위해 만들어진 객체 형태의 포맷

const message = {
  sender: "김코딩",
  receiver: "박해커",
  message: "해커야 오늘 저녁 같이 먹을래?",
  createdAt: "2021-01-12 10:10:10"
}

JSON.stringify : 객체를 JSON으로 변환 (직렬화)
JSON.parse : JSON을 객체로 변환 (역직렬화)

let packet = `{"sender":"김코딩","receiver":"박해커","message":"해커야 오늘 저녁 같이 먹을래?","createdAt":"2021-01-12 10:10:10"}`
let obj = JSON.parse(packet)

console.log(obj)
/*
 * {
 * sender: "김코딩",
 * receiver: "박해커",
 * message: "해커야 오늘 저녁 같이 먹을래?",
 * createdAt: "2021-01-12 10:10:10"
 * }
 */

 console.log(typeof(obj))
 // `object`

오늘의 과제


  • JSON.stringify
function stringifyJSON(obj) {
  if(typeof obj ==='boolean' || typeof obj ==='number' || obj === null) {
    return String(obj);
  }
  if(typeof obj ==='string') {
    return `"${obj}"`;
  }
  if(Array.isArray(obj)) { // 배열일때
    let newArr = [];
    for(let el of obj) {
        newArr.push(stringifyJSON(el));
    } 
    return `[${newArr}]`;
  } else { // 객체일때
    let result = ''
    for(let key in obj) {
      if(obj[key] === undefined || typeof obj[key] === "function"){
        continue;
      }
      result = result + `${stringifyJSON(key)}:${stringifyJSON(obj[key])}`;
    }
    result = result.slice(0, -1);
    return `{${result}}`;
  }
};
  • Tree UI
function createTreeView(menu, currentNode) {
  for (let i = 0; i < menu.length; i++) {
    const li = document.createElement("li");
    if (Object.keys(menu[i]).includes("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);
    }
  }
}

재귀를 코드에 적용하니까 난이도가 확 올라가서 힘들었다.

내가 맞게 하고있는지 궁금해서 GPT한테 물어보고 과제를 진행함

DOM을 이용한 재귀는 아직도 이해가 되지않는다.😔

profile
프론트엔드 개발자 준비 중

0개의 댓글