UNPKG

@ecomplus/utils

Version:

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

65 lines (64 loc) 2.58 kB
"use strict"; require("core-js/modules/es.symbol.js"); require("core-js/modules/es.symbol.description.js"); require("core-js/modules/es.object.to-string.js"); require("core-js/modules/es.symbol.iterator.js"); require("core-js/modules/es.array.iterator.js"); require("core-js/modules/es.string.iterator.js"); require("core-js/modules/web.dom-collections.iterator.js"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; require("core-js/modules/es.array.sort.js"); require("core-js/modules/es.function.name.js"); function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } /** * @method * @memberof ecomUtils * @name alphabeticalSort * @description Sort list of objects alphabetically by name ot title property. * @param {Array|Object.<string, *>} list - Array of objects (products, brands...) or list body with 'results' * @returns {Array} * * @example * // Sample array with name or title's property * ecomUtils.alphabeticalSort(['product', 'category']) * // => ["category", "product"] * ecomUtils.alphabeticalSort(['Matheus', 'Vitor', 'Ana', 'Clara', 'Bruna']) * // => ["Ana", "Bruna", "Clara", "Matheus", "Vitor"] * // Can be an array of objects like: * const brand1 = {name: 'zara'} * const brand2 = {name: 'Thermaltake'} * const brand3 = {name: 'AeroCool'} * const brand4 = {name: 'Fortrek'} * const array = [brand1, brand2, brand3, brand4] * ecomUtils.alphabeticalSort(array) * // => [{name: "AeroCool"}, {name: "Fortrek"}, {name: "Thermaltake"}, {name: "Thermaltake"}, {name: "zara"}] */ var alphabeticalSort = function alphabeticalSort(list) { if (Array.isArray(list)) { // try to sort by name or title return list.sort(function (a, b) { if (a && b) { if (a.name) { // products, categories, brand... return a.name < b.name ? -1 : 1; } else if (a.title) { // grids return a.title < b.title ? -1 : 1; } } // fallback return a < b ? -1 : 1; }); } if (_typeof(list) === 'object' && list !== null) { // suppose to be a 'list all' request body return alphabeticalSort(list.results); } console.error(new Error('`list` should be an array')); // always return an array return []; }; var _default = exports.default = alphabeticalSort;