깊은바다거북
개발 공부 기록
깊은바다거북
전체 방문자
오늘
어제
  • 분류 전체보기 (219)
    • JAVA (9)
    • JavaScript (15)
    • 스파르타코딩클럽 (11)
      • [내일배움단] 웹개발 종합반 개발일지 (5)
      • [내일배움캠프] 프로젝트와 트러블 슈팅 (6)
    • SQL | NoSQL (4)
    • CS 등등 (0)
    • TIL | WIL (173)
    • 기타 에러 해결 (3)
    • 내 살 길 궁리 (4)

인기 글

최근 글

최근 댓글

태그

  • 01. 미니 프로젝트
  • Trie
  • DFS(깊이우선탐색)
  • 코딩테스트 연습문제
  • 팀 프로젝트
  • 트러블 슈팅 Troubleshooting
  • 최대 힙(Max Heap)
  • 최소 힙(Min Heap)
  • Til
  • Binary Tree(이진 트리)
  • 프로그래머스
  • Leetcode
  • TypeScript
  • Inorder Traversal(중위 순회)
  • 자료 구조
  • BFS(너비우선탐색)
  • 자바스크립트 기초 문법
  • 혼자 공부하는 자바스크립트
  • 점화식(Recurrence Relation)
  • 재귀 함수
  • Linked List
  • POST / GET 요청
  • leetcode-cli
  • TIT (Today I Troubleshot)
  • Preorder Traversal(전위 순회)
  • 시간 복잡도
  • 자잘한 에러 해결
  • Backtracking(백트래킹)
  • tree
  • BST(이진 탐색 트리)
hELLO · Designed By 정상우.
깊은바다거북

개발 공부 기록

TIL | WIL

8/18 (금) 양방향 링크드 리스트와 LRU 캐시 디자인 TIL

2023. 8. 18. 22:02

공부한 것

  • LeetCode #146. LRU Cache (캐시 디자인)를 풀었다.
    LeetCode - The World's Leading Online Programming Learning Platform
    Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
    https://leetcode.com/problems/lru-cache/submissions/1024552141/?envType=list&envId=rus4c4ci

알게 된 것

  • 필요한 캐시 자료구조를 만드는 문제를 푸는데 Doubly linked list라는 걸 또 만들어서 사용했다. 여태 Singly linked list만 활용하는 문제를 풀었었는데 양방향(doubly) 클래스와 메소드 작성이 새로웠다.
    /**
     * doubly-linked list 클래스 예시
     * (문제에 맞게 속성과 메소드를 구성함): 
    */
    class DoublyLinkedList {
    	constructor() {
    		this.head = null;
    		this.tail = null;
    		this.length = 0;
    	}
    
    	push(key, val) {
    		const newNode = new Node(key, val);
    		if (!this.head) {
    			this.head = newNode;
    			this.tail = newNode;
    		} else {
    			this.tail.next = newNode;
    			newNode.prev = this.tail;
    			this.tail = newNode;
    		}
    		this.length++;
    		return newNode;
    	}
    
    	remove(node) {
    		if (!node.next && !node.prev) { // 노드가 1개뿐일 때
    			this.head = null;
    			this.tail = null;
    		} else if (!node.next) { // 삭제하려는 노드가 끝 노드일 때
    			this.tail = node.prev;
    			this.tail.next = null;
    		} else if (!node.prev) { // 삭제하려는 노드가 첫 노드일 때
    			this.head = node.next;
    			this.head.prev = null;
    		} else { 
    			const prev = node.prev;
    			const next = node.next;
    			prev.next = next;
    			next.prev = prev;
    		}
    		this.length--;
    	}
    }
  • 또한 function 키워드는 호이스팅이 되는데, class 선언은 안 되는 것 같다. 더 정확히 말하면 function키워드로 인한 함수 선언은 타입1 호이스팅으로, 선언된 스코프 내에서 선언되기 전에도 그 ‘값’을 사용할 수 있는 경우인데 반해 class 키워드는 let과 const와 함께 타입3 호이스팅에 속한다. 변수가 선언된 스코프 내에서 선언되기 전에도 ‘행동의 변화’를 야기하는 타입이라고 안내되어있다. (참고: https://developer.mozilla.org/en-US/docs/Glossary/Hoisting) 어떤 이들은 class와 let, const와를 아예 non-hoisting으로 간주한다는데, 자세한 것은 자바스크립트의 lexical declaration과 temporal dead zone 등에 관한 내용을 탐구해봐야겠다.

    ⇒ 결론은, 그래서 function 키워드는 module.exports로 export하기 전후로 선언한 것이 전부 유효하게 참조되지만 class는 module.exports = {} 다음에 선언되면 참조 에러가 뜨게 되는 것이었다.

    ReferenceError: Cannot access 'LRUCacheDoublyLinkedList' before initialization
    
          297 |
          298 | module.exports = {
        > 299 |     LRUCache: LRUCacheDoublyLinkedList,
              |               ^
          300 | }
          301 |
          302 | class LRUCacheDoublyLinkedList { 
    					// => 호출 이후에 선언된 class는 참조 에러를 발생시킨다


Uploaded by N2T

    'TIL | WIL' 카테고리의 다른 글
    • 8/21 (월) 풀이 제출 후 소요 시간 시각화하기 TIL, TIT
    • 8/19 (토) 퀴즈풀이도 타입스크립트로 써볼까 TIL
    • 8/17 (목) 오버로딩 안되는 JavaScript의 메소드와 속성 TIL
    • 8/16 (수) 링크드 리스트와 재귀함수 점화식 TIL
    깊은바다거북
    깊은바다거북

    티스토리툴바