UNPKG

@ecomplus/utils

Version:

JS utility functions to E-Com Plus (not only) related apps

83 lines (81 loc) 3.26 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; require("core-js/modules/es.object.to-string.js"); require("core-js/modules/web.dom-collections.for-each.js"); var _specTextValue = _interopRequireDefault(require("./spec-text-value")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * @method * @memberof ecomUtils * @name variationsGrids * @description Parse variations specifications to one object only. * @param {Object.<string, *>} product - Product body object * @param {Object.<string, *>} [filterGrids] - Filter object with grids and searched values * @param {boolean} [inStockOnly] - True to consider only variations with positive stock quantity * @param {string} [delimiter=', '] - Delimiter between each specification * @returns {Object.<string, *>} * * @example * // Only param product * const product = { 'name': 'Cruzeiro 2019', 'variations': [ * { 'name': 'Cruzeiro 2019 / P', 'quantity': 10, 'specifications': { 'size': [ { 'text': 'P', 'value': 's' } ] } }, * { 'name': 'Cruzeiro 2019 / M', 'quantity': 10, 'specifications': { 'size': [ { 'text': 'M', 'value': 'm' } ] } }, * { 'name': 'Cruzeiro 2019 / G', 'specifications': { 'size': [ { 'text': 'G', 'value': 'l' } ] }, 'quantity': 0 } * ] } * ecomUtils.variationsGrids(product) * // => {size: [ 'P', 'M', 'G' ]} * // You can also check for product stock to get only variations with available quantity * // Same product above * const inStockOnly = true * ecomUtils.variationsGrids(product, {}, inStockOnly) * // => {size: [ 'P', 'M' ]} */ var variationsGrids = function variationsGrids(product, filterGrids, inStockOnly, delimiter) { var grids = {}; if (product && Array.isArray(product.variations)) { product.variations.forEach(function (variation) { if (inStockOnly && variation.quantity <= 0) { // out of stock return; } var specifications = variation.specifications; // abstraction to get spec text value var specValue = function specValue(grid) { return (0, _specTextValue.default)(variation, grid, delimiter); }; if (specifications) { // check if current variation specs match with filters if (filterGrids) { for (var filter in filterGrids) { if (filterGrids.hasOwnProperty(filter)) { if (!specifications[filter] || specValue(filter) !== filterGrids[filter]) { // does not match filtered grid // skip current variation return; } } } } // get values from each variation spec for (var grid in specifications) { if (specifications.hasOwnProperty(grid)) { var text = specValue(grid); if (!grids.hasOwnProperty(grid)) { grids[grid] = []; } else if (grids[grid].indexOf(text) !== -1) { // current spec value has already been added continue; } grids[grid].push(text); } } } }); } // returns parsed grid object return grids; }; var _default = exports.default = variationsGrids;