웹/JavaScript

자료구조 구현

Stack

const stack = [];

stack.push('a');
stack.push('b');

stack[stack.length - 1 ] // top
stack.pop();

 

Queue

const queue = [];

queue.push('a');
queue.push('b');

queue.shift();
queue.shift();

 

Linked List

const Node = value => {
  return { value, next: null }
}

const list = {
  head: null,
  tail: null,
  add(value) {
    const newNode = Node(value)

    if (list.head) {
      const tailStore = list.tail
      list.tail = newNode
      tailStore.next = list.tail
    } else {
      list.head = newNode
      list.tail = newNode
    }
  },
  removeHead() {
    if (list.head) {
      const headStore = list.head.value
      list.head = list.head.next

      if (list.head === null) {
        list.tail = null
      }

      return `${headStore} is removed`
    }

    return "list is empty"
  },
  contains(value) {
    let head = list.head
    while (head) {
      if (head.value === value) {
        return true
      }
      head = head.next
    }

    return false
  },
}

 

Map

배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환한다.

const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

 

 

Array.prototype.map() - JavaScript | MDN

map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.

developer.mozilla.org

 

Set

 자료형에 관계 없이 원시 값과 객체 참조 모두 유일한 값을 저장할 수 있다.

const set1 = new Set([1, 2, 3, 4, 5]);

console.log(set1.has(1));
// expected output: true

console.log(set1.has(5));
// expected output: true

console.log(set1.has(6));
// expected output: false
 

Set - JavaScript | MDN

Set 객체는 자료형에 관계 없이 원시 값과 객체 참조 모두 유일한 값을 저장할 수 있습니다.

developer.mozilla.org

 

' > JavaScript' 카테고리의 다른 글

모던 자바 스크립트 Deep Dive 21  (0) 2021.08.25
[JS]공부하며 얻은 짧은 팁s.  (0) 2021.08.18
객체와 변경불가성  (0) 2021.08.03
알고리즘 문제풀이 입력 받아오기.  (0) 2021.07.30
객체  (0) 2021.07.29