-
Notifications
You must be signed in to change notification settings - Fork 0
/
skroutz.js
52 lines (44 loc) · 1.76 KB
/
skroutz.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
const SUPPORTED_MEAS_UNITS = ['ml', 'gr'];
window.onload = () => {
if (document.querySelector('.unit-price')) return;
const productCards = getProductCards();
const products = productCards.map(getCardParsed);
products.forEach(({ cardElem, pricePerUnit, unit }) => {
if (!pricePerUnit) return;
const unitPriceElem = document.createElement('span');
unitPriceElem.setAttribute('class', 'unit-price');
const pricePerUnitRounded = Math.round(pricePerUnit * 100) / 100;
const pricePerUnitText = Number(pricePerUnitRounded).toFixed(2).replace('.', ',');
unitPriceElem.innerText = `${pricePerUnitText}€/${unit}`;
const priceLink = cardElem.querySelector('.product-link');
insertAfter(priceLink, unitPriceElem);
});
};
function getProductCards() {
return Array.from(document.querySelectorAll('.cf.card'));
}
function getCardParsed(cardElem) {
const priceElem = cardElem.querySelector('.product-link');
const title = priceElem.title;
const { unit, size } = getSizeUnitOfMeasurement(title);
const price = getPrice(priceElem);
const pricePerUnit = price / size;
return { cardElem, title, unit, size, price, pricePerUnit };
}
function getSizeUnitOfMeasurement(title) {
for(const unit of SUPPORTED_MEAS_UNITS) {
const matches = new RegExp(`^.*\\s+(\\d*${unit})(?:\\s|$)`, 'i').exec(title);
if (!matches || !matches.length) continue;
return { size: matches[1].split(unit)[0], unit };
}
return {};
}
function getPrice(elem) {
const string = elem.innerText
.split(' €')[0]
.replace(',', '.');
return parseFloat(string);
}
function insertAfter(element, newElement) {
element.parentNode.insertBefore(newElement, element.nextSibling);
}