강의

멘토링

커뮤니티

Inflearn Community Q&A

chosohi2108's profile image
chosohi2108

asked

Introduction to Javascript Algorithm Problem Solving (Coding Test Preparation)

5. LRU (Kakao Cache Variant: Insertion Sort Application)

LRU 코드 리뷰 부탁드립니다

Written on

·

276

·

Edited

0

function setQueue(queue, val) {
  if (queue.includes(val)) {
    queue = queue
      .slice(0, queue.indexOf(val))
      .concat(queue.slice(queue.indexOf(val) + 1));
    queue.unshift(val);
  } else {
    queue.pop();
    queue.unshift(val);
  }
  return queue;
}

function solution(s, n, arr) {
  let queue = new Array(s).fill(0);

  for (const val of arr) {
    if (queue.length === s) {
      queue = setQueue(queue, val);
    } else {
      queue = setQueue(queue, val);
    }
  }
  return queue.join(" ");
}

hit, miss 인 경우의 로직을 setQueue로 함수화해서 처리를 해보았는데, 혹시 틀리거나 예외케이스에서 틀릴 경우가 생길까요?

javascript코딩-테스트

Answer 1

1

codingcamp님의 프로필 이미지
codingcamp
Instructor

안녕하세요^^

반례없이 잘 짜신 코드입니다.

아래에서 코드라인이 똑 같은 것을 호출하는데 왜 굳이 if else로 구분해서 호출한 것인지 궁금하네요.

if (queue.length === s) {
      queue = setQueue(queue, val);
    } else {
      queue = setQueue(queue, val);
    }
huisso님의 프로필 이미지
huisso
Questioner

답변 감사합니다!
기존에 분기처리한 흔적을 정리하지 못했네요..!
감사드립니다!

chosohi2108's profile image
chosohi2108

asked

Ask a question