Skip to content

Instantly share code, notes, and snippets.

@doliG
Last active August 14, 2020 07:29
Show Gist options
  • Save doliG/3bb1ce877e7461fa11ff95fb63e273b4 to your computer and use it in GitHub Desktop.
Save doliG/3bb1ce877e7461fa11ff95fb63e273b4 to your computer and use it in GitHub Desktop.
function transform(input) {
return input
.filter(havePrice)
.map(withDiscount)
}
const havePrice = (product) => Boolean(product.price)
function withDiscount(product) {
switch (product.savingsType) {
case 'total':
return withTotalDiscount(product)
case 'percent':
return withPercentDiscount(product)
default:
console.error(`Error: product with unknow savingType '${product.savingsType}'`)
}
}
const withTotalDiscount = ({ price, savings, kind }) => ({
basePrice: `${price} €`,
description: `Vous économisez ${savings} € par rapport au prix initial`,
price: `${price - savings} €`,
savings: `${savings} €`,
title: kindToTitle(kind)
})
const withPercentDiscount =({ price, savings, kind }) => {
const totalSavings = price * (savings / 100)
return {
basePrice: `${price} €`,
description: `Vous économisez ${totalSavings} € par rapport au prix initial`,
price: `${price - totalSavings} €`,
savings: `${savings} %`,
title: kindToTitle(kind)
}
}
const kindToTitle = (discountKind) => {
const titleMap = {
'reductionVoucher': 'Bon de réduction',
'sales': 'Soldes'
}
return titleMap[discountKind] || 'Reduction inconnue'
}
const products = [
{
price: 3000,
kind: 'reductionVoucher',
savings: 300,
savingsType: 'total',
},
{
price: undefined,
kind: 'sales',
savings: 10,
savingsType: 'percent',
},
{
price: 3000,
kind: 'sales',
savings: 15,
savingsType: 'percent',
}
]
console.log(transform(products))
// Note: https://twitter.com/jaffathecake/status/1213077702300852224 ;-)
function transform(input) {
return input.reduce((acc, val) => {
const [key, ...arr] = val
acc[key] = arr
return acc
}, {})
}
const input = [
["key1", 1, 2, 3, 4],
["key2", 4, 5, 6, 7]
]
const transformed = transform(input)
console.log(transformed)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment