TIL | WIL

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

깊은바다거북 2023. 8. 18. 22:02

공부한 것

알게 된 것

  • 필요한 캐시 자료구조를 만드는 문제를 푸는데 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 키워드는 letconst와 함께 타입3 호이스팅에 속한다. 변수가 선언된 스코프 내에서 선언되기 전에도 ‘행동의 변화’를 야기하는 타입이라고 안내되어있다. (참고: https://developer.mozilla.org/en-US/docs/Glossary/Hoisting) 어떤 이들은 classlet, 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