❓ 스택(Stack)이란?

  • LIFO(Last In First Out) 즉, 나중에 넣은 데이터가 먼저 나오는 선형 자료 구조이다.
  • 어디서 스택을 사용하나요? : 컨트롤 + Z, 페이지 이동 후 뒤로가기 등

💡 구현 메서드

초기 데이터 설정 : Stack()

function Stack(array) {
  this.array = array ? array : [];
}

생성자 함수로 초기 데이터 설정

데이터 전체 획득 : Stack.getBuffer()

Stack.prototype.getBuffer = function () {
  return this.array.slice();
};

객체 내 데이터 셋 반환

비어 있는지 확인 : isEmpty()

Stack.prototype.isEmpty = function () {
  return this.array.length === 0;
};

객체 내 데이터 존재 여부 확인

추가 : Stack.push()

Stack.prototype.push = function (element) {
  return this.array.push(element);
};

데이터 추가

삭제 : stack.pop()

Stack.prototype.pop = function () {
  return this.array.pop();
};

데이터 삭제

마지막 데이터 조회 : Stack.peak()

Stack.prototype.peek = function () {
  return this.array[this.array.length - 1];
};

가장 끝 데이터 반환

크기 확인 : Stack.size()

Stack.prototype.size = function () {
  return this.array.length;
};

스택 내 데이터 개수 확인

데이터 위치 : Stack.indexOf()

Stack.prototype.indexOf = function (element, position = 0) {
  // return this.array.indexOf(element, position);
  for (let i = position; i < this.array.length; i++) {
    if (element === this.array[i]) return i;
  }
  return -1;
};

매개변수로 넘어온 값의 위치 확인

존재 여부 확인 : Stack.includes()

Stack.prototype.includes = function (element, position = 0) {
  // return this.array.includes(element);
  for (let i = position; i < this.array.length; i++) {
    if (element === this.array[i]) return true;
  }
  return false;
};

데이터 존재 여부 확인

profile
#UXUI #코린이

0개의 댓글