Last active
August 19, 2018 09:59
-
-
Save m1el/8523135 to your computer and use it in GitHub Desktop.
reddit comment sorting algorithm implemented for habr
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
// License=WTFPLv2 | |
$(function () { | |
function sortCommentList(parent, recursive) { | |
var comments = $(parent).find('>.comment_item'); | |
$(parent).append(keySort(comments, extractRating, true)); | |
recursive && comments.find('>.reply_comments:has(div)').each(function (idx, replies) { | |
sortCommentList(replies, recursive); | |
}); | |
} | |
function extractRating(comment) { | |
try { | |
var title = $(comment).find('>.comment_body .score').attr('title'), | |
mat = /↑(\d+).*?↓(\d+)/.exec('' + title); | |
return mat ? rating(+mat[1], +mat[2]) : 0; | |
} catch (e) { | |
return 0; | |
} | |
} | |
function ratingQ(max, z, cnt, total) { | |
if (!(max > 0 && z > 0 && cnt >= 0 && total >= 0)) { | |
return 0; | |
} | |
if (cnt === 0) { | |
return 0; | |
} | |
var t = 2 * (total / max) / (z * z), | |
ph = (total / max) / cnt; | |
return max * (t * ph + 1 - Math.sqrt(2 * t * ph * (1 - ph) + 1)) / (t + 2); | |
} | |
function rating(pos, neg) { | |
return ratingQ(1, 1.6, (pos + neg), pos); | |
} | |
function keySort(arr, keyFn, reverse) { | |
return arr.slice().sort(function (a, b) { | |
var ka = keyFn(a), | |
kb = keyFn(b); | |
return ka === kb ? 0 : (ka > kb) ^ !reverse ? 1 : -1; | |
}); | |
} | |
sortCommentList($('#comments'), true); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment