Created
January 17, 2022 21:32
-
-
Save ubershmekel/64f8e24a77d4b1f18865e1be65ec227c to your computer and use it in GitHub Desktop.
Sort the front page of hacker news by score with this bookmarklet. Save it as a bookmark.
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
javascript: function findNodes(el) { | |
return el.querySelectorAll('.score'); | |
} | |
function isDigit(str) { | |
return str.length === 1 && str.match(/[0-9]/i); | |
} | |
function metricVal(el) { | |
let modifiers = { | |
K: 1e3, | |
M: 1e6, | |
B: 1e9, | |
}; | |
let text = findNodes(el)[0]?.textContent.trim(); | |
if (!text) { | |
console.log('empty text'); | |
return NaN; | |
}; | |
const match = text.match(/\d+(\.\d+)?[KMB]?/); | |
if (!match) { | |
console.log("bad parse " + text); | |
return NaN; | |
} | |
const numText = match[0]; | |
let number; | |
if (isDigit(numText[numText.length - 1])) { | |
number = +numText; | |
} else { | |
number = +numText.slice(0, -1); | |
const modChar = match[0].slice(-1); | |
number = number * modifiers[modChar]; | |
} | |
return number; | |
} | |
function compare(el1, el2) { | |
let val1 = metricVal(el1.tr); | |
let val2 = metricVal(el2.tr); | |
if (val1 < val2) return 1; | |
if (val1 > val2) return -1; | |
return 0; | |
} | |
function findCommonParent(el1, el2) { | |
const seen = new Set(); | |
let next = el1; | |
while (next) { | |
seen.add(next); | |
next = next.parentNode; | |
} | |
next = el2; | |
while (next) { | |
if (seen.has(next)) { | |
return next; | |
} else { | |
next = next.parentNode; | |
} | |
} | |
return null; | |
} | |
function main() { | |
let nodes = findNodes(document); | |
let topNode = findCommonParent(nodes[0], nodes[1]); | |
const items = []; | |
[...nodes].map(node => { | |
const tr = node.parentNode.parentNode; | |
const titleTr = tr.previousSibling; | |
items.push({ | |
tr, | |
titleTr, | |
}); | |
}); | |
items.sort(compare); | |
items.map((item) => { | |
topNode.appendChild(item.titleTr); | |
topNode.appendChild(item.tr); | |
}) | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment