해결법을 알아보기 전에 먼저 push() 메서드로 인해 발생하는 문제부터 살펴봅시다.

    장바구니 상품 목록을 받아서 내용을 요약하는 간단한 함수를 생각해봅시다. 이 함수는 할인 금액을 확인하고 할인 상품이 두 개 이상이면 오류 객체를 반환합니다. 만약 오류가 없다면 상품을 많이 구매한 사람에게 사은품을 줍니다.

    arrays/push/push.js

    const cart = [{
        name: 'The Foundation Triology',
        price: 19.99,
        discount: false,
      },
      {
        name: 'Godel, Escher, Bach',
        price: 15.99,
        discount: false,
      },
      {
        name: 'Red Mars',
        price: 5.99,
        discount: true,
      },
    ];
    const reward = {
      name: 'Guide to Science Fiction',
      discount: true,
      price: 0,
    };
     
    function addFreeGift(cart) {
      if (cart.length > 2) {
        cart.push(reward);
        return cart;
      }
      return cart;
    }
     
    function summarizeCart(cart) {
      const discountable = cart.filter(item => item.discount);
      if (discountable.length > 1) {
        return {
          error: '할인 상품은 하나만 주문할 수 있습니다.',
        };
      }
      const cartWithReward = addFreeGift(cart);
      return {
        discounts: discountable.length,
        items: cartWithReward.length,
        cart: cartWithReward,
      };
    }

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.