[0521] FixedArray

한별·2024년 5월 21일

스파르타 내배캠 TIL

목록 보기
23/63

오늘은 알고리즘 심화반 과제인 FixedArray 구현을 완료했다.
생성자와 push, pop, getLength, stringify 함수를 구현했다.

class FixedArray {
  #arrayLength;
  #array;
  #currentLength;

  // #arrayLength와 #array를 알맞게 초기화
  // 생성자 파라미터에는 FixedArray의 고정된 길이를 받아야됨.
  // #array초기화 시 각요소의 값은 undefined
  constructor(size) {
    this.#arrayLength = size;
    this.#array = [];
    this.#currentLength = 0;
  }

  // 배열 맨 뒤에 요소 추가
  // 배열의 길이가 #arrayLength를 초과할 경우 요소를 추가되면 안됨.
  push(element) {
    if (this.#currentLength === this.#arrayLength)
      throw new Error("배열의 크기를 초과합니다");
    this.#array[this.#currentLength++] = element;
  }

  // 배열의 맨 마지막 요소를 제거하고 그 요소를 반환
  pop() {
    if (this.#currentLength === 0) throw new Error("삭제할 요소가 없습니다");
    return this.#array[--this.#currentLength];
  }

  // 현재 배열의 사용되고 있는 크기를 반환
  getLength() {
    return this.#currentLength;
  }

  // 현재 배열의 상태를 string으로 반환
  stringify() {
    let str = "[";
    for (var idx = 0; idx < this.#arrayLength; idx++) {
      str += idx === 0 ? this.#array[idx] : `, ${this.#array[idx]}`;
    }
    str += "]";
    return str;
  }
}

// test
const arr = new FixedArray(5);
arr.push(0);
arr.push(1);
arr.push(2);
arr.push(3);
arr.push(4);
// arr.push(5);
console.log(arr.pop());
console.log(arr.pop());
console.log(arr.pop());
console.log(arr.pop());
console.log(arr.pop());
// console.log(arr.pop());
console.log(arr.stringify());

잘 작동하니 기분이 좋았다.
딱히 막히는 부분은 없었는데
throw Error() 랑 throw new Error() 가 둘 다 똑같은 느낌이었어서
약간 차이가 궁금해졌다.
근데 구글링했는데 이해를 못하겠다 ;<
튜터님한테 한번에 후다다다ㅏ 물어봐야겠다.

질문 리스트는
1. 피카츄 배구 왜 dependency array에 coord 넣어줘야 했는가 (state가 계속 초기화 됐는가)
2. throw Error와 throw new Error의 차이점

코드카타

코드카타 문제 3개 풀었다 ㅎㅎㅎ
오랜만에~
백준허브가 정상 작동 안 하더니..
갑자기 되더라..
너무 열 받는데 기분 좋잖슴~~ ㅎㅎㅎ히히히히

profile
글 잘 쓰고 싶어요

0개의 댓글