-
Notifications
You must be signed in to change notification settings - Fork 1
/
categories-list.js
48 lines (46 loc) · 1.55 KB
/
categories-list.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* @method
* @memberof ecomUtils
* @name categoriesList
* @description Parse category tree string to list of categories names.
* @param {Object.<string, *>|string} product - Product object body or category tree string
* @returns {Array}
*
* @example
* // Can be a category tree, like:
* const categoryTree = 'Quarto > Cama > Travesseiros'
* // So use categoryTree is parameter of function categoriesList, like:
* ecomUtils.categoriesList(categoryTree)
* // => ["Quarto", "Cama", "Travesseiros"]
* // Or can be a product body object like:
* const product = { name: 'Ultimate', categories: [{name: 'Cadeira Gamer'},{name: 'Periféricos'}]}
* ecomUtils.categoriesList(product)
* => ["Cadeira Gamer"]
*/
const categoriesList = product => {
let categoryTree
if (typeof product === 'object' && product !== null) {
// try to get categories from product body object
if (product.category_tree) {
categoryTree = product.category_tree
} else if (Array.isArray(product.categories) && product.categories[0]) {
// use the first category from list
return [ product.categories[0].name ]
}
} else {
// category tree string received as param ?
categoryTree = product
}
if (typeof categoryTree === 'string') {
const categories = categoryTree.split('>')
for (let i = 0; i < categories.length; i++) {
// remove white spaces from names
categories[i] = categories[i].trim()
}
// list of category names
return categories
}
// fallback returning empty array
return []
}
export default categoriesList