Created
June 9, 2019 21:35
-
-
Save tinacious/1ff7ff60fd3c0fe4e4381c38b34c4a09 to your computer and use it in GitHub Desktop.
Bookmarklet for Well.ca to display price per unit of measurement
This file contains hidden or 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
/** | |
* Show price per quantity | |
* If the price per unit is greater than the average, it displays in red. | |
* Example: https://i.imgur.com/dvu0o4c.png | |
* Usage: | |
* 1. Copy the code | |
* 2. In an existing bookmark in Chrome, type `javascript:` (omit the surrounding ticks) | |
* 3. Paste the contents of this code after `javascript:` | |
*/ | |
(() => { | |
const comparedItems = []; | |
/** | |
* Element selectors | |
*/ | |
const productSelector = '.product-item-info'; | |
const productPriceSelector = '.product_grid_price'; | |
const quantitySelector = '.product_grid_info_subtitle'; | |
const $products = $(productSelector).map((i, element) => { | |
const $product = $(element); | |
/* if there's more than one price, grab the last one, which is the reduced price */ | |
const $priceContainer = $product.find(productPriceSelector); | |
const prices = $priceContainer.text().split('$'); | |
const currentPrice = Number(prices[prices.length - 1]); | |
/* get the number from the product info */ | |
const quantity = Number($product.find(quantitySelector).text().replace(/[^0-9]/g, '')); | |
/* math it */ | |
const pricePerUnit = (currentPrice / quantity).toFixed(2); | |
/* insert into the DOM */ | |
$('<div>').css({ | |
padding: 6, | |
fontWeight: 700, | |
position: 'relative', | |
zIndex: 10 | |
}) | |
.addClass('price-per-unit') | |
.text(`$${pricePerUnit} per unit`) | |
.appendTo($priceContainer); | |
const data = { | |
quantity, | |
currentPrice, | |
pricePerUnit: Number(pricePerUnit) | |
}; | |
comparedItems.push(data); | |
$product.__data = data; | |
return $product; | |
}); | |
const filtered = comparedItems.filter(({ quantity }, i) => quantity > 0); | |
/* calculate average price */ | |
const sortedByPricePerUnit = filtered.sort((a, b) => a.pricePerUnit - b.pricePerUnit); | |
const sumOfPricePerUnit = sortedByPricePerUnit.reduce((sum, current) => { | |
return sum + current.pricePerUnit; | |
}, 0); | |
const averagePrice = sumOfPricePerUnit / sortedByPricePerUnit.length; | |
/* display how item compares to average price -> if greater than average price, make red */ | |
$products.each((i, element) => { | |
const data = element.__data; | |
const $pricePerUnit = $(element).find('.price-per-unit'); | |
if (data.pricePerUnit > averagePrice) { | |
$pricePerUnit.css({ color: 'red' }); | |
} | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment