Last active
March 29, 2021 17:19
-
-
Save erwanriou/cef6e4b3034ad9c91d9c9641febe150f to your computer and use it in GitHub Desktop.
vanilla javascript update to calculate price discount for ecommerce.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const handlePricePourcentage = () => { | |
const isEmpty = value => | |
value === undefined || | |
value === null || | |
(typeof value === "object" && Object.keys(value).length === 0) || | |
(typeof value === "string" && value.trim().length === 0) | |
// GET REAL PRICE | |
const getRealPrice = () => { | |
const parent = document.getElementsByTagName("del") | |
return Object.values(parent).map(tag => { | |
const items = tag.getElementsByTagName("bdi") | |
return Object.values(items).map(tag => Number(tag.innerHTML.split(" ")[0].split(',').join('').split('.').join('')))[0] | |
}) | |
} | |
// GET DISCOUNTEDPRICE | |
const getDiscountedPrice = () => { | |
const parent = document.getElementsByTagName("ins") | |
return Object.values(parent).map(tag => { | |
const items = tag.getElementsByTagName("bdi") | |
return Object.values(items).map(tag => Number(tag.innerHTML.split(" ")[0].split(',').join('').split('.').join('')))[0] | |
}) | |
} | |
// GET DISCOUNT | |
const getDiscount = () => { | |
const realPrices = getRealPrice() | |
const discountedPrices = getDiscountedPrice() | |
return discountedPrices.map((price,i) => ({ | |
fullPrice: realPrices[i], | |
discountedPrice: price, | |
discount: parseFloat(100 - (100 * price / realPrices[i])).toFixed(0) | |
})) | |
} | |
// INJECT DISCOUNT | |
const injectHtml = () => { | |
const discounts = getDiscount() | |
const wrappers = document.getElementsByTagName("ins") | |
return Object.values(wrappers).map((wrapper, i) => { | |
let span = document.createElement('span') | |
span.innerHTML = `${discounts[i].discount}%` | |
span.classList.add("discount-percentage"); | |
return wrapper.appendChild(span) | |
}) | |
} | |
injectHtml() | |
} | |
handlePricePourcentage() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment