5. Size & Color Picker Availability
A sneaker comes in several colors and sizes. Each color/size combination is a separate variant with its own stock, and some combinations were never produced.
When a shopper picks "White", sizes that are sold out in white must appear disabled, but the other colors must stay clickable so the shopper can switch. Getting this wrong either hides products that are in stock (lost sales) or lets people add sold-out variants to the cart (cancelled orders).
Your task:
Write getSelectableOptions(product, selection). For every option, return the values the shopper can click right now.
Input:
- product.options: the options and their values in display order, for example [{ name: "color", values: ["Black", "White"] }, { name: "size", values: ["S", "M", "L"] }].
- product.variants: [{ options: { color: "Black", size: "M" }, stock: 4 }, ...].
- selection: the shopper's current choice, possibly partial, for example { color: "White" }.
Rules:
- A value v of option O is selectable when some variant with stock > 0 has O = v and matches every selected value of the other options. The option's own current selection is ignored, so the shopper can switch it.
- Return { [optionName]: [selectable values] } with the values in the order of product.options. Include every option, even when its list is empty.
- Combinations with no variant are unavailable.
Examples
Example 1
- Input
product = { options: [ { name: "color", values: ["Black", "White"] }, { name: "size", values: ["S", "M", "L"] } ], variants: [ { options: { color: "Black", size: "S" }, stock: 0 }, { options: { color: "Black", size: "M" }, stock: 4 }, { options: { color: "Black", size: "L" }, stock: 2 }, { options: { color: "White", size: "S" }, stock: 5 }, { options: { color: "White", size: "M" }, stock: 0 } ] }selection = { color: "White" }
- Output
{ color: ["Black", "White"], size: ["S"] }
- Explanation
- Colors are judged without the color selection, so Black stays clickable. Sizes are judged for White only: M is sold out and L does not exist.
Solution
Write getSelectableOptions. Tab indents (Esc then Tab leaves the editor), Ctrl/⌘ + Enter runs. Each run has a 3-second limit. Your code is saved in this browser.
Test Results
Click "Run Code" to test your solution.