Skip to content

Instantly share code, notes, and snippets.

@phiresky
Last active December 10, 2023 18:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phiresky/59c2926ab9c7013da6f32df47e24520d to your computer and use it in GitHub Desktop.
Save phiresky/59c2926ab9c7013da6f32df47e24520d to your computer and use it in GitHub Desktop.
reorders amazon search results to sort by price per weight to find the actually cheapest item (only tested on amazon.de)
// reorders amazon search results to sort by price per weight to find the actually cheapest item
// 1. install https://addons.mozilla.org/en-US/firefox/addon/weautopagerize/
// 2. search for something
// 3. scroll down all the way
// 4. run this script
// "featured by amazon"
for (let crap of document.getElementsByClassName(
"template=FEATURED_ASINS_LIST"
))
crap.remove();
function isHidden(el) {
return el.offsetParent === null;
}
selectorItem = ".s-asin .sg-col-inner";
selectorPPU = ".a-text-normal .a-size-base.a-color-secondary";
getcur = () => $$(selectorItem).filter((x) => !isHidden(x));
tonum = ({ num, unit }) => {
const unitmap = {
kg: 1,
"100g": 0.1,
"100 g": 0.1,
g: 0.001,
gramm: 0.001,
stück: 0.001, // fake
unit: 0.001,
beutel: 0.001,
};
const div = unitmap[unit.toLowerCase()];
if (!div) throw Error(`unknown unit: ${unit}`);
const res = +num.replace(".", "").replace(",", ".") / div;
if (isNaN(res)) throw Error(`nan: ${num}/${unit}`);
return res;
};
sorted = $$(selectorItem)
.filter((x) => !isHidden(x))
.map((ele) => {
const ppu = ele.querySelector(selectorPPU);
return {
ele,
txt: ppu?.textContent,
val: ppu
? tonum(
/\((?<num>[\d.]+,\d+)\s+€\/(?<unit>.*)\)/.exec(
ppu.textContent
).groups
)
: 9999999,
};
})
.sort((a, b) => a.val - b.val);
function swapElements(obj1, obj2) {
// create marker element and insert it where obj1 is
var temp = document.createElement("div");
obj1.parentNode.insertBefore(temp, obj1);
// move obj1 to right before obj2
obj2.parentNode.insertBefore(obj1, obj2);
// move obj2 to right before where obj1 used to be
temp.parentNode.insertBefore(obj2, temp);
// remove temporary marker node
temp.parentNode.removeChild(temp);
}
(async () => {
for (var i = 0; i < sorted.length; i++) {
if (i % 10 === 0) console.log(`${i}/${sorted.length}`);
// await new Promise(r => setImmediate(r));
var curlist = getcur();
swapElements(curlist[i], sorted[i].ele);
}
console.log("done!");
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment