묻고 답해요
161만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결비전공자의 전공자 따라잡기 - 자료구조(with JavaScript)
숙제 length return 하기
class Node { constructor(value) { this.value = value; this.left = null; this.right = null; } } class BinarySearchTree { constructor() { this.root = null; // 숙제 몇개 인지 확인하는 count this.length = 0; } #insert(node, value) { if (node.value > value) { // 루트노드보다 작은 값이면 if (node.left) { this.#insert(node.left, value); } else { node.left = new Node(value); } } else { // 숙제 : 같은 값을 넣은경우 에러 처리 (alert, throw) if (node.value === value) throw new Error(`이미 해당 ${value}가 존재 합니다`); // 루트노드보다 큰 값이면 if (node.right) { this.#insert(node.right, value); } else { node.right = new Node(value); } } } insert(value) { if (!this.root) { this.root = new Node(value); } else { this.#insert(this.root, value); } this.length++; } #search(node, value) { if (!node) return null; if (node.value > value) { return this.#search(node.left, value); } else if (node.value === value) { return node; } else { return this.#search(node.right, value); } // if (node.value > value) { // // 더 작은값 찾을때 // if (!node.left) { // return null; // } // if (node.left.value === value) { // return node.left; // } // return this.#search(node.left, value); // } else { // if (!node.right) { // return null; // } // if (node.right.value === value) { // return node.right; // } // return this.#search(node.right, value); // } } search(value) { if (!this.root) return null; if (this.root.value === value) { return this.root; } return this.#search(this.root, value); } #remove(node, value) { if (!node) { // 제거 할 값이 bst에 존재하지 않는 경우 return null; // 지울 값이 존재 안하면 null return } if (node.value === value) { // 자식 입장 // 지울 값을 찾은 경우 if (!node.left && !node.right) { this.length--; // leaf return null; } else if (!node.left) { // 왼팔만 없는 경우 return node.right; // 왼팔이 없는 경우 자기 왼팔 대신 오른팔을 쓰라고 return 해줌 } else if (!node.right) { // 오른팔만 없는 경우 return node.left; // 오른팔 없는 경우 자기 오른팔 대신 왼팔을 쓰라고 return 해줌 } else { // 양팔 다 있는 경우 let exchange = node.left; while (exchange.right) { exchange = exchange.right; } const temp = node.value; node.value = exchange.value; exchange.value = temp; node.left = this.#remove(node.left, exchange.value); return node; } } else { // 부모 입장 if (node.value > value) { node.left = this.#remove(node.left, value); return node; } else { node.right = this.#remove(node.right, value); return node; } } } remove(value) { // 1. leaf(양팔 다 없음) -> 제거 // 2. leaf x, 왼팔이 없다 -> 오른팔 끌어올린다 // 3. leaf x, 오른팔이 없다 -> 왼팔 끌어올린다 // 4. leaf x, 양팔 다 있다 -> 왼팔에서 가장 큰 애와 바꾼다, leaf를 지운다 this.root = this.#remove(this.root, value); // return 숙제 length return 하기 return this.length; } } const bst = new BinarySearchTree(); bst.insert(8); bst.insert(10); bst.insert(3); bst.insert(1); bst.insert(14); bst.insert(6); bst.insert(7); bst.insert(4); bst.insert(13); console.log(bst.length); // 9 console.log(bst.remove(8)); // 8 bst.search(7); bst.search(5); console.log(bst.remove(4)); // 7 console.log(bst.remove(15)); // 없는 값을 지운다면 현재 length return 7 숙제 정답일까요?제발 ㅠㅠ 🙏
-
해결됨실무에 바로 적용하는 프런트엔드 테스트 - 1부. 테스트 기초: 단위・통합 테스트
4.4 getBy~, queryBy~ 질문입니다
마지막, 삭제 버튼 테스트Q. 삭제 버튼을 누르면 TableRow가 사라지니까 queryByText('text').not.toBeInTheDocument()를 사용해서 유무를 확인 하셨는데getByText('text').not.toBeInTheDocument()를 사용해서 해당 텍스트가 있는 요소가 없으면 에러가 나타나도록 유도해서 테스트 검증할 수도 있지 않나요?? 가능은 한건지, 권장이 되지 않는건지 질문 드립니다
-
미해결비전공자의 전공자 따라잡기 - 자료구조(with JavaScript)
숙제 : 같은 값을 넣은경우 에러 처리
class Node { constructor(value) { this.value = value; this.left = null; this.right = null; } } class BinarySearchTree { constructor() { this.root = null; } #insert(node, value) { if (node.value > value) { // 루트노드보다 작은 값이면 if (node.left) { this.#insert(node.left, value); } else { node.left = new Node(value); } } else { // 숙제 : 같은 값을 넣은경우 에러 처리 (alert, throw) if (node.value === value) throw new Error(`이미 해당 ${value}가 존재 합니다`); // 루트노드보다 큰 값이면 if (node.right) { this.#insert(node.right, value); } else { node.right = new Node(value); } } } insert(value) { if (!this.root) { this.root = new Node(value); } else { this.#insert(this.root, value); // 숙제 : 같은 값을 넣은경우 에러 처리 (alert, throw) } } search(value) {} remove(value) {} } const bst = new BinarySearchTree(); bst.insert(8); //bst.insert(8); // Error: 이미 해당 8가 존재 합니다 bst.insert(10); //bst.insert(10); // Error: 이미 해당 10가 존재 합니다 bst.insert(3); //bst.insert(3); // Error: 이미 해당 3가 존재 합니다 bst.insert(1); //bst.insert(1); // Error: 이미 해당 1가 존재 합니다 bst.insert(14); //bst.insert(14); // Error: 이미 해당 14가 존재 합니다 bst.insert(6); //bst.insert(6); // Error: 이미 해당 6가 존재 합니다 bst.insert(7); //bst.insert(7); // Error: 이미 해당 7가 존재 합니다 bst.insert(4); //bst.insert(4); // Error: 이미 해당 4가 존재 합니다 bst.insert(13); //bst.insert(13); // Error: 이미 해당 13가 존재 합니다숙제 코드 정답일까요?
-
해결됨비전공자의 전공자 따라잡기 - 자료구조(with JavaScript)
영상 중간에 0:10 1:23초 수정에 따른 코드 최종본
class Node { constructor(value) { this.value = value; this.left = null; this.right = null; } } class BinarySearchTree { constructor() { this.root = null; } #insert(node, value) { if (node.value > value) { // 루트노드보다 작은 값이면 if (node.left) { this.#insert(node.left, value); } else { node.left = new Node(value); } } else { // 루트노드보다 큰 값이면 if (node.right) { this.#insert(node.right, value); } else { node.right = new Node(value); } } } insert(value) { if (!this.root) { this.root = new Node(value); } else { this.#insert(this.root, value); // 숙제 : 같은 값을 넣은경우 에러 처리 (alert, throw) } } search(value) {} remove(value) {} } const bst = new BinarySearchTree(); bst.insert(8); bst.insert(10); bst.insert(3); bst.insert(1); bst.insert(14); bst.insert(6); bst.insert(7); bst.insert(4); bst.insert(13); 영상 따라 했는데 안되면 해당 코드 참고 해보세용!
-
미해결인터랙티브 웹 개발 제대로 시작하기
동적으로 html 생성 후 이벤트 위임 질문 있습니다.
안녕하세요. 이벤트 위임 연습하다가 변칙적으로 연습하고 있는데요. 동적으로 html 생성 된 후에 버튼에 ''-active"클래스 추가 하면 실제로 클래스가 추가가 안되네요. 그런데 elem을 consol 창에 찍어보면 "-avtive"클래스가 추가된 요소로 나오는데 이건 무슨 문제일까요?<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>스크립트 연습</title> <style> *, *::before, *::after {margin:0; padding:0; box-sizing:border-box;} h1 {padding:20px 0;} h2 {padding-bottom:20px;} li {list-style:none;} .container {max-width:1000px; margin:0 auto; padding:0 20px; background-color:#f1f1f1;} .wrap {padding:40px; border:1px solid #888;} .wrap + .wrap {margin-top:50px;} .btn-list {display:flex; justify-content:space-between; gap:20px; width:100%; padding:20px; background-color:dodgerblue;} .btn-list li {width:calc(100% / 3);} .btn-list__item {width:100%; padding:10px;} .btn-list__item.-active {background-color:darkkhaki;} </style> </head> <body> <div class="container"> <h1>스크립트 연습</h1> <section class="wrap btn-wrap"> <h2>버튼 연습</h2> <ul class="btn-list"> <!-- <li class="asdf"><button class="btn-list__item"><span>버튼</span> 1버튼</button></li> <li class="asdf"><button class="btn-list__item"><span>버튼</span> 2버튼</button></li> <li class="asdf"><button class="btn-list__item"><span>버튼</span> 3버튼</button></li> --> </ul> </section> <script> window.addEventListener('DOMContentLoaded', initHandler) function initHandler() { buttonListHandler(); } function buttonListHandler() { const btnWrap = document.querySelector('.btn-wrap'); const btnList = document.querySelector('.btn-list'); let currentItem = null; function clickHandler(el) { let elem = el.target; while (!elem.classList.contains('btn-list__item')){ elem = elem.parentNode; // console.log(elem) if(elem.nodeName === 'BODY'){ elem = null; return; } } if(currentItem){ currentItem.classList.remove('-active'); } if(elem.classList.contains('btn-list__item')){ elem.classList.add('-active'); currentItem = elem; } console.log(elem); } btnWrap.addEventListener('click', ()=> { const htmlStr = ` <li><button class="btn-list__item"><span>버튼</span> 1버튼</button></li> <li><button class="btn-list__item"><span>버튼</span> 2버튼</button></li> <li><button class="btn-list__item"><span>버튼</span> 3버튼</button></li> `; btnList.innerHTML = htmlStr; }) btnWrap.addEventListener('click', clickHandler); } </script> </div> </body> </html>
-
해결됨Vue.js 끝장내기 - 실무에 필요한 모든 것
AppHeader.vue에 vue 디폴트 만들에 Delete `␍` 오류나면
Delete ␍ 오류나면prettier/prettier 쪽에 아래것 추가,endOfLine: 'auto',
-
미해결인터랙티브 웹 개발 제대로 시작하기
rotateY()에서 deg에 따른 차이
오른쪽 벽에서 transform을아래와 같이 설정하면 브라우저를 통해 보여지는 길이가 다릅니다. 이유가 뭘까요?transform: rotateY(-90deg) translateZ(400vw);
-
해결됨Next.js 시작하기
Link 컴포넌트의 prefetching 기능
안녕하세요! Link 컴포넌트의 prefetching 기능에 대해 궁금한 점이 있어 질문 남깁니다. 뷰포트에 들어오는 Link 영역에 대해 미리 데이터를 끌어온다고 하셨는데, 어느 정도 범위까지 데이터를 끌어오는걸까요? 만약 그 링크로 연결된 페이지가 서버 사이드 렌더링을 이용하는 페이지라면 페이지를 미리 그려서 HTML 파일을 완성하는 수준까지 prefetching을 하는 걸까요?
-
미해결SCSS(SASS)+FLEX 실전 반응형 웹 프로젝트 with Figma
실수로 style.css를 지워버렸습니다...
실수로 style.css파일을 지워서 다시 만들려고 style.scss에 watch sass를 눌렀는데 css파일이 다시 생기지가 않아요.. 해결 방법이 없을까요...? ㅠㅠ
-
미해결[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core
오류로 인해 더 이상 진행이 어려워 문의합니다.
강의 잘 듣고 있습니다.아래 이미지와 같은 오류가 뜨면서 여러가지(db 삭제, Docker 재 시작, 서버 재 구동, debugger 로 확인..등) 해 봤는데, 원인을 찾을 수가 없어 강사님께 도움 청합니다.이 전까지 잘 진행되고 있었고, 현재 진행하는 강좌도 반복해 확인 해 봤는데...위와 같은 이미지 내용만 봐서 찾기 힘드시겠지만, 혹시 하는 심정으로~~도움 부탁 드립니다. 꾸~벅.
-
해결됨만들면서 배우는 리액트: 컴포넌트 설계와 리팩토링
콘솔 에뮬레이터 cmder이 회사 컴퓨터에서 차단 당해요
이 에뮬레이터 사용하지 않고 터미널 이용해도 수업 진행에 지장 없을까요?
-
해결됨한 입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지
동적경로 사용 오류
안녕하세요. Route 부분에 오류가 생겼는데 어떤 부분이 잘못되었는지 모르겠어서 질문 남깁니다.Route 함수에 path 경로를 설정할 때, 동적경로를 설정하고 싶으면 ":"과 함께 파라미터의 값을 적어주는 것으로 압니다. 강사님께서 적은 코드와 제 코드가 다른 점이 없는데, 저는 해당 url에 접근했을 때 url경로에 ':'이 포함되어서 나옵니다. 구글링+gpt를 사용해서 해당 오류를 고치려고 해보았지만 찾을 수 없는 상태입니다. 어떤 부분이 문제일까요? import "./App.css"; import { useReducer, useRef, createContext } from "react"; import { Routes, Route } from "react-router-dom"; import Home from "./Pages/Home"; import New from "./Pages/New"; import Diary from "./Pages/Diary"; import Edit from "./Pages/Edit"; import Notfound from "./Pages/Notfound"; function reducer(state, action) { switch (action.type) { case "CREATE": return [action.data, ...state]; case "UPDATE": return state.map((item) => String(item.id) === String(action.data.id) ? action.data : item ); case "DELETE": return state.filter((item) => String(item.id) !== String(action.data.id)); default: return state; } } const mockData = [ { id: 1, createdData: new Date("2024-06-12").getTime(), emotionId: 1, content: "1번 일기 내용", }, { id: 2, createdData: new Date("2024-06-11").getTime(), emotionId: 2, content: "2번 일기 내용", }, { id: 3, createdData: new Date("2024-05-11").getTime(), emotionId: 3, content: "3번 일기 내용", }, ]; export const DiaryStateContext = createContext(); export const DiaryDispatchContext = createContext(); function App() { const [data, dispatch] = useReducer(reducer, mockData); const idRef = useRef(3); // 새로운 일기 추가 const Create = (createdData, emotionId, content) => { dispatch({ type: "CREATE", data: { id: idRef.current++, createdData, emotionId, content, }, }); }; // 기존 일기 수정 const Update = (id, createdData, emotionId, content) => { dispatch({ type: "UPDATE", data: { id, createdData, emotionId, content, }, }); }; // 기존 일기 삭제 const Delete = (id) => { dispatch({ type: "DELETE", data: { id, }, }); }; return ( <> <DiaryStateContext.Provider value={data}> <DiaryDispatchContext.Provider value={{ Create, Update, Delete }}> <Routes> <Route path="/" element={<Home />} /> <Route path="/new" element={<New />} /> <Route path="/diary/:id" element={<Diary />} /> <Route path="/edit/:id" element={<Edit />} /> <Route path="*" element={<Notfound />} /> </Routes> </DiaryDispatchContext.Provider> </DiaryStateContext.Provider> </> ); } export default App;
-
미해결[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core
nestjs 자료 다운로드 받을 수 있다고 하는데, 찾아봐도 도저히 못찾겠네요 어디서 찾을 수 있나요?
nestjs 자료 다운로드 받을 수 있다고 하는데, 찾아봐도 도저히 못찾겠네요 어디서 찾을 수 있나요?
-
해결됨Vue.js 끝장내기 - 실무에 필요한 모든 것
vue3로 따라오시다가 import axios 에러 뜨시는 분들
jest.config.js 파일에서preset 밑에 transformIgnorePatterns: ['node_modules/(?!axios)'],이거 한 줄 추가해주시면 됩니다..이유는 axios 버전이 높아서 jest에서 es6를 인식 못하는것이 문제라고 합니다.. 감사합니다..
-
미해결비전공자의 전공자 따라잡기 - 자료구조(with JavaScript)
숙제2 연결리스트를 이용하여 큐 구현하기
학습 목표- 배열 치트키 자료구조가 아닌 연결 리스트를 이용하여 queue 자료구조를 구현하자.- 삽입과 삭제를 시간복잡도 O(1)가 되게 해야됨.- queue은 FIFO이기 때문에 삭제시 첫번째를 삭제해야됨.class Node { constructor(value) { this.value = value; this.next = null; this.prev = null; } } class LinkedList { constructor(length = 0) { this.length = length; this.head = null; this.tail = null; } add(value) { const newNode = new Node(value); if (this.head === null) { this.head = newNode; this.tail = newNode; } else { newNode.prev = this.tail; this.tail.next = newNode; this.tail = newNode; } this.length++; return this.length; } // 스택 구현시 삭제 메서드 removeLast() { const value = this.tail.value; this.tail.prev.next = null; // 제일 마지막 이전의 next의 좌표를 null로 변경해줌 this.tail = this.tail.prev; // 마지막을 tail의 이전 노드로 변경 해줌 return value; } // 큐 구현시 삭제 메서드 removeFirst() { const value = this.head.value; this.head.next.prev = null; // 제일 첫번째 다음의 이전 좌표를 null로 변경해줌 this.head = this.head.next; // 첫번째를 head next 노드로 변경 해줌 return value; } } // 숙제2 연결리스트로 큐 만들기 class Queue { linkedList = new LinkedList(); add(value) { return this.linkedList.add(value); } shift() { return this.linkedList.removeFirst(); } get top() { return this.linkedList.head.value; } get length() { return this.linkedList.length; } } const queue = new Queue(); console.log(queue.add(1)); // 1 console.log(queue.add(3)); // 2 console.log(queue.add(5)); // 3 console.log(queue.top); // 1 console.log(queue.length); // 3 console.log(queue.shift()); // 1 결과head의 value값이 3, prev가 null이 되고 next가 value가 5인 노드를 가르킴
-
미해결비전공자의 전공자 따라잡기 - 자료구조(with JavaScript)
숙제1 LinkedList로 스택 구현하기
학습 목표- 배열 치트키 자료구조가 아닌 연결 리스를 이용하여 stack 자료구조를 구현하자.- 삽입과 삭제를 시간복잡도 O(1)가 되게 해야됨.- stack은 FILO이기 때문에 삭제시 마지막을 삭제해야됨. class Node { constructor(value) { this.value = value; this.next = null; this.prev = null; } } class LinkedList { constructor(length = 0) { this.length = length; this.head = null; this.tail = null; } add(value) { const newNode = new Node(value); if (this.head === null) { this.head = newNode; this.tail = newNode; } else { newNode.prev = this.tail; this.tail.next = newNode; this.tail = newNode; } this.length++; return this.length; } removeLast() { const value = this.tail.value; this.tail.prev.next = null; // 제일 마지막 이전의 next의 좌표를 null로 변경해줌 this.tail = this.tail.prev; // 마지막을 tail의 이전 노드로 변경 해줌 return value; } } // 숙제 1 연결리스트로 스택 만들기 class Stack { linkedList = new LinkedList(); add(value) { return this.linkedList.add(value); } pop() { return this.linkedList.removeLast(); } get top() { return this.linkedList.head.value; } get length() { return this.linkedList.length; } } const stack = new Stack(); console.log(stack.add(1)); // 1 console.log(stack.add(3)); // 2 console.log(stack.add(5)); // 3 console.log(stack.top); // 1 console.log(stack.length); // 3 console.log(stack.pop()); // 5결과디버거 결과를 확인 해보면 최종적으로tail의 value는 3이고 next는 null prev는 value1의 노드를 가르키고 있는걸 알 수 있다.
-
미해결자바스크립트 알고리즘 문제풀이 입문(코딩테스트 대비)
이중 for로만 간단하게 풀어봤습니다. 괜찮을까요?
const solve = (arr) => { let count = 0; let u = 0; let r = 0; let d = 0; let l = 0; for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr.length; j++) { let my = arr[i][j] u = i !== 0 ? arr[i - 1][j] : 0 r = j !== arr.length - 1 ? arr[i][j + 1] : 0 d = i !== arr.length - 1 ? arr[i + 1][j] : 0 l = j !== 0 ? arr[i][j - 1] : 0 if (my > u && my > r && my > d && my > l) { count += 1 } } } return count }
-
미해결[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core
onDelete 실행 시 대상 entity 가 null, 관계 Entity가 삭제되지 않는 현상
typeORM은 0.3.17 입니다. 말 그대로 UserModel 에서 OneToOne 의 relation option "'onDelete: CASCADE'" 로 profile entity 를 삭제했을때 UserModel 이 삭제되지 않고, profile 이 null 로 표기되는 현상입니다.
-
해결됨한 입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지
투두 추가할 때 onChangeContent 작성 이유
8.4) Create - 투두 추가하기 강의를 들으며 4분대 경 코드를 작성 중입니다. import "./Editor.css"; import { useState } from "react"; const Editor = ({ onCreate }) => { const [content, setContent] = useState(""); const onChangeContent = (e) => { setContent(e.target.value); }; const onSubmit = () => { onCreate(); }; return ( <div className="Editor"> <input value={content} onChange={onChangeContent} placeholder="새로운 Todo..." /> <button onClick={onSubmit}>추가</button> </div> ); }; export default Editor;이 부분에서, input에 들어가는 content는 추가 버튼을 클릭할 때만 value를 setContent로 해줘도 될 것 같은데요, 왜 onChangeContent로 값이 바뀔 때마다 밸류를 저장해주는지 궁금합니다. 타이핑할때마다(값이 바뀔 때마다) 저장할 필요없이 마지막에 추가할 때만 저장되어도 되지 않나 싶어서 궁금해졌습니다.
-
미해결자바스크립트 알고리즘 문제풀이 입문(코딩테스트 대비)
강사님 이렇게 풀어봤습니다.!
const solve = (arr) => { const result = [] for (let i = 0; i < arr.length; i++) { let count = 1 for(let j = 0; j < arr.length; j++) { if (arr[j] > arr[i]) { count += 1; } } result.push(count); } return result }조금 간단...해..보이게..?처음에 count 를 1로 줘서 1등으로 시작하고 풀이해주신 부분과 비슷하지만 살짝은,, 다르게 풀어봤습니다.