-
Notifications
You must be signed in to change notification settings - Fork 0
/
products.js
95 lines (80 loc) · 2.69 KB
/
products.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const { default: axios } = require("axios");
const processProductsArray = async () => {
const products = await retrieveProductArray()
const averagePrice = calculateProductArrayAveragePrice(products)
const highestPriceProduct = getHighestPriceProductOfProductArray(products)
const categories = getCategories(products)
const averagePricesByCategories = createAveragePriceArrayByCategories(categories, products)
const highestPriceProductsByCategories = createHighestPriceProductArrayByCategories(categories, products)
return {
averagePrice,
highestPriceProduct,
averagePricesByCategories,
highestPriceProductsByCategories
}
}
const retrieveProductArray = async () => {
const { data: products } = await axios.get(
"https://fakestoreapi.com/products"
)
return products
}
const calculateProductArrayAveragePrice = (products) => {
return products.reduce(
(totalPrice, currentProduct) => totalPrice + currentProduct.price,
0
) / products.length;
}
const getHighestPriceProductOfProductArray = (products) => {
return products.reduce(
(maximumPriceProduct, currentProduct) =>
currentProduct.price > maximumPriceProduct.price
? currentProduct
: maximumPriceProduct,
products[0]
)
}
const getCategories = (products) => {
return removeDuplicatesFromStringArray(products.map(product => product.category))
}
const filterProductsByCategory = (category, products) => {
return products.filter(product => product.category === category)
}
const removeDuplicatesFromStringArray = (stringArray) => {
return Array.from(new Set(stringArray))
}
const createAveragePriceArrayByCategories = (categories, products) => {
let averagePrices = []
for (const category of categories) {
const productsByCategory = filterProductsByCategory(category, products)
const averagePrice = calculateProductArrayAveragePrice(productsByCategory)
averagePrices.push({
averagePrice,
category
})
}
return averagePrices
}
const createHighestPriceProductArrayByCategories = (categories, products) => {
let highestPriceProducts = []
for (const category of categories) {
const productsByCategory = filterProductsByCategory(category, products)
const highestPriceProduct = getHighestPriceProductOfProductArray(productsByCategory)
highestPriceProducts.push({
highestPriceProduct,
category
})
}
return highestPriceProducts
}
module.exports = {
processProductsArray,
retrieveProductArray,
getCategories,
removeDuplicatesFromStringArray,
createAveragePriceArrayByCategories,
calculateProductArrayAveragePrice,
filterProductsByCategory,
createHighestPriceProductArrayByCategories,
getHighestPriceProductOfProductArray
}