UNPKG

1.05 kBJavaScriptView Raw
1/**
2 * TODO Document
3 */
4export const findMatchingVariant = ({
5 variants,
6 optionCodes,
7 optionSelections
8}) => {
9 return variants.find(({ attributes, product }) => {
10 const customAttributes = (attributes || []).reduce(
11 (map, { code, value_index }) => new Map(map).set(code, value_index),
12 new Map()
13 );
14
15 for (const [id, value] of optionSelections) {
16 const code = optionCodes.get(id);
17 const matchesStandardAttribute = product[code] === value;
18 const matchesCustomAttribute = customAttributes.get(code) === value;
19
20 // if any option selection fails to match any standard attribute
21 // and also fails to match any custom attribute
22 // then this isn't the correct variant
23 if (!matchesStandardAttribute && !matchesCustomAttribute) {
24 return false;
25 }
26 }
27
28 // otherwise, every option selection matched
29 // and this is the correct variant
30 return true;
31 });
32};