Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
HackerNews "Who is Hiring" Search w/ Date Sorting
function query() {
var SORT_RECENT_FIRST = true;
var SEARCH_REPLIES = true;
var query_list = Array.prototype.slice.call(arguments);
var commentTable = document.querySelector('.comment-tree');
var commentNodes = Array.prototype.slice.call(commentTable.querySelectorAll('.athing'));
var COMMENT_TEXT_SELECTOR = '.c5a,.cae,.c00,.c9c,.cdd,.c73,.c88';
var DEPTH_SELECTOR = '.ind img',
DATE_SELECTOR = '.age a',
DEPTH_LIMIT = 40,
DATE_REGEX = /id=(\d+)/i;
// If we have a RegEx, return it
// Otherwise make it a case insensitive regex.
function destring(what) {
return what.test ? what : new RegExp(what.toString(), 'i');
}
var Comment = function(node, index) {
var depth = node.querySelector(DEPTH_SELECTOR);
var text = node.querySelectorAll(COMMENT_TEXT_SELECTOR);
var date = node.querySelector(DATE_SELECTOR);
date = (date && date.href) ? date.href.match(DATE_REGEX) : [];
this.date = (typeof date[1] !== 'undefined') ? +date[1] : 0;
this.depth = (depth && depth.width) ? +(depth.width) : 0;
this.text = (text && text.length) ? text[0].innerHTML.trim() : '';
this.childText = '';
this.nodes = [node];
};
Comment.prototype.display = function(state) {
this.nodes.forEach(function(node) {
node.style.display = state;
});
};
Comment.prototype.search = function(query_list) {
var self = this;
return query_list.some(function(query) {
if (query.forEach) {
return query.map(destring).some(function(query) {
return self.single_query_search(query);
});
} else {
query = destring(query);
return self.single_query_search(query);
}
});
};
Comment.prototype.single_query_search = function(destringed_query) {
if (this.text.search(destringed_query) > 1) {
return true;
}
if (SEARCH_REPLIES) {
return this.childText.search(destringed_query) > -1;
}
return false;
};
var groupedComments = function() {
var grouped = [];
var comment = {};
var lastRoot = {};
commentNodes.forEach(function(node, index) {
comment = new Comment(node, index);
if (comment.depth < DEPTH_LIMIT) {
grouped.push(comment);
lastRoot = comment;
} else {
lastRoot.nodes.push(node);
lastRoot.childText += comment.text;
}
});
return grouped;
};
var sortedTbody = document.createElement('tbody');
var sortedComments = groupedComments().sort(function(a, b) {
return (a.date > b.date) ? -1 : 1;
});
var shown = 0, total = sortedComments.length;
sortedComments.forEach(function(comment) {
if (comment.search(query_list)) {
shown++;
comment.display('block');
} else {
comment.display('none');
}
comment.nodes.forEach(function(node) {
sortedTbody.appendChild(node);
});
});
// Remove the existing tbody
while(commentTable.lastChild) {
commentTable.removeChild(commentTable.lastChild);
}
commentTable.appendChild(sortedTbody);
return {shown: shown, total: total}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment