Skip to content

Instantly share code, notes, and snippets.

@svaksha
Forked from meiamsome/hn_search.js
Last active September 12, 2015 11:52
Show Gist options
  • Save svaksha/789b0d5be0489dee6895 to your computer and use it in GitHub Desktop.
Save svaksha/789b0d5be0489dee6895 to your computer and use it in GitHub Desktop.
hn job query search
// takes arguments and produces an array of functions that accept context
function handle_args() {
var args = Array.prototype.slice.call(arguments);
return args.map(function(arg) {
if(arg instanceof Function) return arg; // Presumably already a contex-accepting function.
if(arg instanceof Array) return and.apply(this, arg); // make arrays behave as and.
// Presuming a string, build a function to check.
var my_regex = new RegExp(arg.toString(), 'i');
return function(context) {
return context.search(my_regex) > -1;
};
});
}
// Perform a logical and on any number of arguments.
function and() {
var args = handle_args.apply(this, arguments);
return function(context) {
return args.every(function(a) {return a(context);});
}
}
// Perform a logical not. This function is also the NAND function, so accepts multiple arguments.
function not() {
var result = and.apply(this, arguments);
return function(context) {
return !result(context);
}
}
nand = not;
// Performs an or using De Morgan's laws
function or() {
var args = handle_args.apply(this, arguments);
return nand.apply(this, args.map(function(a) {return not(a)}));
}
// Performs an XOR. This only works for two inputs.
function xor() {
if(arguments.length != 2) throw "XOR takes two arguments only.";
return and(or.apply(this, arguments), not(and.apply(this, arguments)));
}
function query() {
var
total = 0, shown = 0,
// HN is done with very unsemantic classes.
job_list = Array.prototype.slice.call(document.querySelectorAll('.c5a,.cae,.c00,.c9c,.cdd,.c73,.c88')),
query = or.apply(this, arguments);
// This traverses up the dom stack trying to find a match of a specific class
function up_to(node, klass) {
if (node.className === klass) {
return node;
}
if(node === document.body) {
throw new Exception();
}
return up_to(node.parentNode, klass);
}
function display(node, what) {
up_to(node, 'athing').style.display = what;
}
// Check each job for a match, and show it if it matches.
job_list.forEach(function(node) {
if(query(node.innerHTML)) {
display(node, 'block');
shown ++;
} else display(node, 'none');
total ++;
});
return {shown: shown, total: total}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment