Skip to content

Instantly share code, notes, and snippets.

@askinss
Created September 6, 2021 10:58
Show Gist options
  • Save askinss/e2b6a96efb6a7d214c592aed21b9ac5b to your computer and use it in GitHub Desktop.
Save askinss/e2b6a96efb6a7d214c592aed21b9ac5b to your computer and use it in GitHub Desktop.
Cart
import json
# Within this challenge, you need to design a "shopping cart". You already have:
# 1. The definition of a "cart item"; a class that describes an entry within the "cart".
# 2. The definition of a "stock snapshot"; a class that describes an amount of stock available for a given item.
# Your task is to implement the "Cart".
# In the first part of this exercise, you should implement the "purchaseable_items" method. This method receives
# a set of products, and a set of "stock snapshots". You need to determine which if the cart items supplied are
# actually purchasable.
# In this initial pass, you should only need to modify purchasable_items
class CartItem:
"""A representation of a given product that the users would like to add to their cart.
"""
def __init__(self, item_id, product_group, product_id, product_price):
self.item_id = item_id
self.product_group = product_group
self.product_id = product_id
self.product_price = product_price
class StockSnapshot:
"""A representation of the quantity of items available in a given "warehouse" (or stock pool)
"""
def __init__(self, product_id, quantity):
self.product_id = product_id
self.quantity = quantity
class Cart:
"""TODO: Implement this
Cart represents the items that the user intends to purchase.
"""
def purchasable_items(self, cart_items, stock_snapshots):
# check for product in cart_items that are in StockSnapshot
self.cart_items = cart_items
purchasable_items = []
self.stock_snapshots = stock_snapshots
for item in cart_items:
for stock in stock_snapshots:
#print(item.product_id,stock.product_id)
if item.product_id == stock.product_id:
purchasable_items.append(item,stock)
print(purchasable_items)
return purchasable_items
# Example
if __name__ == '__main__':
item_a = CartItem("1", "t-shirt", "t-shirt-m", 5.0)
item_b = CartItem("2", "t-shirt", "t-shirt-m", 5.0)
snapshot_a = StockSnapshot("1", 15.0)
snapshot_b = StockSnapshot("2", 0.0)
cart = Cart()
purchasable = cart.purchasable_items([item_a, item_b], [snapshot_a, snapshot_b])
for p in purchasable:
print(json.dumps(p.__dict__))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment