Skip to content

4주차 과제 구현#3

Open
jinvicky wants to merge 2 commits intoCodeSoom:mainfrom
jinvicky:jin_four_week
Open

4주차 과제 구현#3
jinvicky wants to merge 2 commits intoCodeSoom:mainfrom
jinvicky:jin_four_week

Conversation

@jinvicky
Copy link

@jinvicky jinvicky commented Oct 8, 2023

No description provided.

Comment on lines +19 to +23
this.#arr.forEach((item, arrIdx) => {
if (item.key === key) {
idx = arrIdx;
}
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

배열을 순회해서 주어진 키에 해당하는 index를 찾기 위해서 forEach메서드를 활용하셨네요. forEach메서드는 주어진 배열을 모두순회하는 메서드이기 때문에 의도가 다르게 전달될 수 있어요. 여기서는 주어진 키만 찾으면 탐색을 그만둬야 하기 때문이죠. 따라서 for문을 사용해서 찾으면 그만두던지 아니면 findIndex를 사용할 수 있어요.

See also

Comment on lines +27 to +36
put(key, value) {
if (this.#size === 0 || this.getKey(key) === undefined) {
const obj = { key: key, value: value };
this.#arr.push(obj);
this.#size++;
} else if (this.#size > 0 && this.getKey(key) !== undefined) {
// 좀 더 조건식을 고칠 수 있을 거 같은데 널체크나 0 길이 체크 시 계속 || && 에러낸다..
this.#arr[this.getKey(key)].value = value;
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image

경우에 수를 따져보면 이렇게 될 것 같아요. 이건 조건문으로 만들면 다음과 같아요.

if (this.#size === 0) {
  // size가 0
} else {
  // size가 0이 아님
  if (this.getKey(key) === undefined) {
    // getKey가 undefined
  } else {
    // getKey가 undefined가 아님
  }
}

조건문을 사용할 때는 이렇게 진리표를 만들지 않으면 무조건 헷갈립니다. 어려워요. 놓칠 수가 있어요. 그래서 이렇게 진리표를 만들고 하나하나씩 확인해가면서 해야 빠트리지 않습니다. 각 경우를 테스트 코드를 작성해야 놓치는 버그가 없어요.

Comment on lines +44 to +50
delete(key) {
const arrKey = this.getKey(key);
if (arrKey !== undefined) {
delete this.#arr[arrKey];
this.#size--;
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

삭제하기 위해서 Array의 해당하는 키를 삭제하고 크기를 줄이셨네요.

Array에서 어떤 값을 삭제하면 한 칸씩 밀어줘야 합니다.

예를들어서 [1, 2, 3, 4, 5]에서 index 2에 해당하는 3을 삭제한다고 해보죠.

delete this.#arr[arrKey];
this.#size--;

만 하게 되면 [1, 2, undefined, 4] 이렇게 됩니다. 그렇게 되면 의도하지 않은 5가 삭제가 되죠?

  delete(key) {
    const arrKey = this.getKey(key);
    if (arrKey !== undefined) {
      // 해당하는 키가 덮어써짐
      for (let i = arrKey; i < this.#size - 1; i++) {
        this.#arr[i] = this.#arr[i + 1];
      }
      
      this.#size--;
    }
  }

그러면 [1, 2, 4, 5]가 되어 3이 삭제가 됩니다.
따라서 배열에서는 값을 삭제하고, 뒤에 배열들을 하나씩 밀어줘야 합니다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants