Skip to content

Instantly share code, notes, and snippets.

@haochi
Created January 10, 2013 05:54
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save haochi/4499779 to your computer and use it in GitHub Desktop.
Save haochi/4499779 to your computer and use it in GitHub Desktop.
Simple reddit messages search. Idea from /r/SomebodyMakeThis, http://redd.it/169agn.
(function ($) {
search(prompt("Enter Search Term:"));
function search(term, after) {
$.getJSON("/message/messages.json", {after: after}, function (res) {
var messages = res.data.children
, stop = false;
for (var i = 0, l = messages.length; i < l; i++) {
var message = messages[i];
if (message_a_match(message, term)) {
var stop = confirm_with_user(message, term);
if(stop){
redirect_to(message);
break;
}
}
}
if (!stop) {
if(res.data.after){
search(term, res.data.after);
}else{
alert("Reached the end of messages.");
}
}
});
}
function redirect_to(message){
window.location = "/message/messages/" + message.data.id;
}
function confirm_with_user(message, term){
var data = message.data
, subject = data.subject
, body = data.body;
return confirm([
"Found a message containing your search term: " + term,
"Is this what you are looking for?",
"",
"Subject: " + subject,
"Body:",
body
].join("\n"));
}
function message_a_match(message, term){
var subject = message.data.subject.toLowerCase()
, body = message.data.body.toLowerCase()
, search_term = term.toLowerCase();
return ~subject.indexOf(search_term) || ~body.indexOf(search_term);
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment