TIL – 쇼핑몰 프로젝트


서버에 저장된 장바구니, 오랜 고민 끝에 드디어 탄생.

쇼핑몰 프로젝트 33일차. 서버 카트 구현 완료.

금방 끝낼 수 있을 줄 알았는데 이제 드디어 서버 카트 구현을 마쳤습니다.

여러 가지 이유가 있지만 첫 번째는 내가 본 것에 속았기 때문입니다.

자바스크립트에서 객체의 동질성을 비교하는 것이 어색한데 아래와 같이 Cart 객체에 임의의 ID 값을 할당하여 관리하고 있는데 Java에서 그대로 가져와서 사용하도록 수정해 보았습니다.

class Cart {
  constructor(items = new Map()) {
    this.items = items;
  }

  generateId() {
    const items = (...this.items.keys())
      .reduce(
        (acc, name) => (...acc, ...this.items.get(name)),
        (),
      );

    const id = Math.max(0, ...items.map((item) => item.id)) + 1;

    return id;
  }

  addItem(item) {
    const { name } = item;
    const { quantity } = item;
    const index = this.findIndex(name, item);

    return index < 0
      ? this.insertItem(name, item)
      : this.updateItem(name, index, quantity);
  }

  insertItem(name, item) {
    if (this.items.size === 0) {
      return new Cart(
        new Map().set(name, (
          { ...item, id: this.generateId() },
        )),
      );
    }
...

그런데 문제는 상품을 장바구니에 담기 전에는 ID가 생성되지 않는다는 점입니다. ID를 얻으려면 장바구니에 상품을 한 번 추가하고 장바구니에 있는 모든 상품을 추출한 다음 조건으로 필터를 실행하고 방금 장바구니에 추가한 상품의 ID를 설정합니다.

그래서 그 ID 값을 서버에 전달하고 카드 키로 설정하고 토스트했는데 자바스크립트가 뽑은 저녁을 먹으러 마트에 갈 정도로 내가 멍청한 이유를 알았다.

여하튼 서버 카트는 성공적으로 구현되었고 이제 상품 리뷰만 하면 됩니다.

그리고 코딩 워크숍을 하면서 오랜만에 마음에 드는 방식으로 문제를 풀고 녹음을 했습니다.

나중에 프로그래밍 실력이 향상되면 객체로 프로그래밍 문제를 해결하는 기사를 게시하는 것이 재미있을 것 같은 느낌이 듭니다.

class Solution {
    public int solution(int cacheSize, String() cities) {
        Database database = new Database(cacheSize);

        int time = database.search(cities, 0, 0, 0);

        return time;
    }
}

class Database {
     private final Cache cache;

    public Database(int cacheSize) {
        this.cache = new Cache(cacheSize);
    }

    public int search(String() cities, int index, int hit, int miss) {
        if (index == cities.length) {
            return getProcessTime(hit, miss);
        }

        if (cache.match(cities(index).toLowerCase())) {
            return search(cities, index + 1, hit + 1, miss);
        }

        return search(cities, index +1, hit, miss + 1);
    }

    private int getProcessTime(int hit, int miss) {
        return hit * 1 + miss * 5;
    }
}

class Cache {
    private int size;
    private LinkedList<String> storage = new LinkedList<>();

    public Cache(int cacheSize) {
        this.size = cacheSize;
    }

    public boolean match(String city) {
        if (size == 0) {
            return false;
        }
        
        if (storage.contains(city)) {
            if (storage.size() == size) {
                storage.remove(city);
                storage.addFirst(city);

                return true;
            }
            
            storage.addFirst(city);

            return true;
        }

        if (storage.size() == size) {
            storage.removeLast();
            storage.addFirst(city);

            return false;
        }

        storage.addFirst(city);

        return false;
    }
}