본문 바로가기
기초다지기/JS 코딩테스트

javaScript 캐시 계산

by 김빵그 2024. 1. 15.

https://school.programmers.co.kr/learn/courses/30/lessons/17680

 

문제 

LRU 알고리즘 코드 , 캐시에서 가장 최근에 사용되지 않은 데이터를 제거

풀이 

function solution(cacheSize, cities) {
    const cache = [];

    return cities.reduce((totalTime, city) => {
        const lowerCity = city.toLowerCase();
        
        if (cache.includes(lowerCity)) {
            // Cache hit
            totalTime++;
            cache.splice(cache.indexOf(lowerCity), 1);
        } else {
            // Cache miss
            totalTime += 5;
        }

        cache.push(lowerCity);
        if (cache.length > cacheSize) {
            cache.shift();
        }

        return totalTime;
    }, 0);
}
  • cacheSize (캐시의 최대크기) , cities (도시 이름 배열) 
  • cache = [] : 초기화 하여 도시 이름 저장
  • reduce
    • cities 배열을 순회하며 총 시간을 누적한다
    • lowerCity : 도시 이름 대소문자 구분하지 않게 비교위해 소문자 변환
    • lowerCity가 이미 캐시에 있다면 캐시 히트 : 총 시간을 1 증가 시키고 , 해당 도시를 캐시에서 제거한 후 다시 앞으로 옮김
    • 캐시에 없다면 캐시 미스로 간주하고 +5
  • push
    • lowerCity를 캐시에 추가
    • 만약 캐시가 최대크기 cacheSize 초과하면 가장 오래된 요소를 캐시의 맨 앞에서 제거
  • totalTime : 총 시간 반환

 

 

다른 풀이

function solution(cacheSize, cities) {
    const MISS = 5, HIT = 1;

    if (cacheSize === 0) return MISS * cities.length;

    let answer = 0,
        cache = [];

    cities.forEach(city => {
        city = city.toUpperCase();

        let idx = cache.indexOf(city);

        if (idx > -1) {
            cache.splice(idx, 1);
            answer += HIT;
        } else {
            if (cache.length >= cacheSize) cache.shift();
            answer += MISS;
        }

        cache.push(city);
    });

    return answer;
}
  • Miss, hit 상수로 정의
  • 캐시 사이즈 0 처리 : 캐시 크기가 0이라면 모든 도시는 미스로 처리
  • forEach
    • idx > -1 캐시에 도시가 있는 경우, 해당 도시 캐시에서 제거하고 Hit 더함
    • 도시가 없는 경우 idx === =1 miss 값 더하고 캐시 꽉하면 가장 오래된 도시 제거
  • 캐시 업데이트
function solution(cacheSize, cities) {
    const cache = new Map();

    const cacheHit = (city) => {
        cache.delete(city);
        cache.set(city, city);
        return 1;
    };

    const cacheMiss = (city) => {
        if (cacheSize === 0) return 5;
        if (cache.size === cacheSize) cache.delete(cache.keys().next().value);
        cache.set(city, city);
        return 5;
    };

    const getTimeCache = (city) => (cache.has(city.toLowerCase()) ? cacheHit : cacheMiss)(city.toLowerCase());

    return cities.map(getTimeCache).reduce((totalTime, current) => totalTime + current, 0);
}