0
$\begingroup$

I'm working on an e-commerce application where users can add stand-alone products like speaker or they can add a bundle product like desktop that has options like mouse, keyboard etc. All the products and options are finally added as cart items to the cart.

For example

Desktop
  - Mouse
  - Keyboard
Speaker

After adding above the cart will have items like below,

Shopping Cart
  Line item 1 - Desktop - Parent-Line NULL
  Line Item 2 - Mouse - Parent-Line Item 1
  Line Item 3 - Keyboard - Parent-Line Item 1
  Line Item 4 - Speaker - Parent-Line NULL

If I remove the product desktop from the cart all of it's options should also be removed. At the same time we want to access all the line items as an array too.

For example,

for (var items in shoppingCart.items) {
  console.log(item);
}

// "Desktop", "Mouse", "Keyboard", "Speaker"

If I use an array to store the items then I need to work on the logic to remove the child options on removing parent. I couldn't come-up with an excellent data structure to solve this problem. Any ideas would be very helpful.

$\endgroup$
1
  • $\begingroup$ Shouldn't it be "Keyboard - Parent-Line Item 1" instead of "Keyboard - Parent-Line Item 2" since item 1 is parent of Keyboard? $\endgroup$ Dec 13, 2020 at 9:37

2 Answers 2

1
$\begingroup$

A bundle looks a multi set of options.
The shopping cart looks a multi set of products.
Don't roll your own implementation when you don't need to.

$\endgroup$
0
$\begingroup$

A tree data structure is a natural way to store this data. It supports all of the operations you listed.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.