Skip to content

Instantly share code, notes, and snippets.

@tristanperalta
Created February 22, 2014 06:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tristanperalta/9149560 to your computer and use it in GitHub Desktop.
Save tristanperalta/9149560 to your computer and use it in GitHub Desktop.
require 'uri'
require 'net/http'
require 'json'
uri = URI('http://www.reddit.com/r/showerthoughts.json')
response = Net::HTTP.get_response(uri)
json = JSON.parse(response.body)
title = json["data"]["children"][rand(25)]["data"]["title"]
puts title
@rstacruz
Copy link

#!/usr/bin/env node
/**
 * showerthoughts          # show all thoughts
 * showerthoughts -r       # show random order of thoughts
 * showerthoughts -1       # show top thought
 * showerthoughts -r -1    # show random thought
 */

var http = require('http');

subreddit('showerthoughts', function (err, data) {
  var thoughts = titles(data);
  if (hasFlag('-r')) thoughts = shuffle(thoughts);
  if (hasFlag('-1')) thoughts = [thoughts[0]];
  console.log(thoughts.join("\n"));
});

function subreddit (name, callback) {
  http.get({ host: 'www.reddit.com', path: '/r/'+name+'.json', method: 'GET' }, function (res) {
    var pageData = "";
    res.setEncoding('utf8');
    res.on('data', function (chunk) { pageData += chunk; });
    res.on('end', function () {
      callback(null, JSON.parse(pageData));
    });
  });
}

function titles (data) {
  return data.data.children.map(function (post) {
    return post.data.title;
  });
}

function shuffle (o){
  for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
  return o;
}

function hasFlag (flag) {
  return process.argv.indexOf(flag) > -1;
}

@rstacruz
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment