Skip to content

Commit

Permalink
1- Preserve compatibility with previous implementation
Browse files Browse the repository at this point in the history
2- Change foreach for reduce
  • Loading branch information
RomuloDevelop committed Jun 11, 2024
1 parent 6fe0064 commit 2b89955
Showing 1 changed file with 36 additions and 16 deletions.
52 changes: 36 additions & 16 deletions common/js/variant-selector-script.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ const VariantSelector = (
quantity: 1,
color: undefined,
size: undefined,
attributes_definition: [],
attributes: {},
},
triggers: {
buyNow: "",
Expand Down Expand Up @@ -240,32 +242,50 @@ const VariantSelector = (

if (!quantity) throw new Error("VariantSelector: No quantity");

const color =
typeof config.product.color === "function"
? config.product.color()
: config.product.color;
const { attributes_definition, attributes } = config.product;
let attributesToValue = {};

if (!color) throw new Error("VariantSelector: No color");
if (attributes_definition.length && Object.keys(attributes).length) {
attributesToValue = attributes_definition.reduce(
(result, attributeName) => {
const variant = attributes[attributeName];
const value = typeof variant === "function" ? variant() : variant;

const size =
typeof config.product.size === "function"
? config.product.size()
: config.product.size;
if (!value) {
throw new Error(`VariantSelector: No ${attributeName}`);
}

result[attributeName] = value;
}
);
} else {
const color =
typeof config.product.color === "function"
? config.product.color()
: config.product.color;

if (!color) throw new Error("VariantSelector: No color");

if (!size) throw new Error("VariantSelector: No size");
const size =
typeof config.product.size === "function"
? config.product.size()
: config.product.size;

if (!size) throw new Error("VariantSelector: No size");

attributesToValue[ATTRIBUTES.Color] = color;
attributesToValue[ATTRIBUTES.Size] = size;
}

Utils.setLoading();

const variantFound =
state.product.variations_definition.product_variations.find((variant) => {
const isTheRightVariant = variant.variation_attributes.every(
(attribute) => {
if (attribute.name === ATTRIBUTES.Color) {
return attribute.value === color;
}
if (attribute.name === ATTRIBUTES.Size) {
return attribute.value === size;
}
const value = attributesToValue[attribute.name];

if (value) return attribute.value === value;

return false;
}
Expand Down

0 comments on commit 2b89955

Please sign in to comment.