Input
categories
- an array of categories
[
{ id: 1, title: 'Smartphones' },
{ id: 2, title: 'Laptops' }
]
products
- an array of products, linked to categories
[
{ id: 1, title: 'iPhone X', category_id: 1, price_min: 1200, price_max: 1700 },
{ id: 2, title: 'MacBook Pro Retina 13', category_id: 2, price_min: 1500, price_max: 4500 },
{ id: 3, title: 'Samsung Galaxy S8', category_id: 1, price_min: 0, price_max: 0 }
]
Output
[
"*Smartphones*\niPhone X\n ($1200 - $1700)\nSamsung Galaxy S8 (free)",
"*Laptops*\nMacBook Pro Retina 13 ($1500 - $4500)"
]
Current implementation
function printPriceList (categories, products) {
return categories.map(category => {
const pcontent = products
.filter(product => product.category_id === category.id)
.map(product => {
const samePrice = product.price_min === product.price_max
const price = samePrice ? product.price_min : `${product.price_min} - ${product.price_max}`
if (price === 0) {
return `${product.title} (free)`
}
return `${product.title} ($${price})`
})
return [`*${category.title}*`].concat(pcontent)
}).map(cat => cat.join('\n'))
}
I'd like to find out a way to refactor it to be more readable, easy to understand and efficient.
What can we use?
- all the modern JS features, like a spread operator (
...smth
) - lodash