#! /usr/bin/env node
var request = require('request')

function randomRevisitor (type, cb) {
  if(typeof type === 'function'){
    cb = type
    type = null
  }

  request.get('http://hub.revisit.link/services',{json:true}, function (err, res) {
    if (err) { return cb(err) }
    var rando = rand(res.body.services, type)
    if(!rando) { return cb(new Error('No online services found' + (type ? ' that support ' + type : '')))}
    cb(null, rando.url)
  })
}

function rand (arr, type) {
  if(type) {arr = filterByType(arr, type)}
  arr = arr.filter(onlineOnly)
  return arr[Math.floor(Math.random()*arr.length)]
}

function filterByType (arr, type) {
  if(type === 'jpg'){type='jpeg'}
  function supportsType(svc) {
      return svc.supports.indexOf(type) > -1
  }
  return arr.filter(supportsType)
}

function onlineOnly (svc) {
    return svc.online
}

module.exports = randomRevisitor

if (!module.parent) {
  randomRevisitor(process.argv[2], function (er, url) {
    if (er) {
      console.error(er)
      process.exit(1)
    }
    console.log(url)
  })
}

@@ -296,368 +296,719 @@
 and(
-res.body.services, type)%0A    if(!rando) %7B return cb(new Error('No online services found' + (type ? ' that support ' + type : '')))%7D%0A    cb(null, rando.url)%0A  %7D)%0A%7D%0A%0Afunction rand (arr, type) %7B%0A  if(type) %7Barr = filterByType(arr, type)%7D%0A  arr = arr.filter(onlineOnly)%0A  return arr%5BMath.floor(Math.random()*arr.length)%5D%0A%7D%0A%0Afunction filterByType (arr, type) %7B
+%0A                  where(%0A                    res.body.services, %5B%0A                      isOnline,%0A                      supports(type)%0A                    %5D%0A                  )%0A                )%0A%0A    if(!rando) %7B return cb(new Error('No online services found' + (type ? ' that support ' + type : '')))%7D%0A    cb(null, rando.url)%0A  %7D)%0A%7D%0A%0Afunction rand (arr) %7B%0A  return arr%5BMath.floor(Math.random()*arr.length)%5D%0A%7D%0A%0Afunction where(arr, predicates) %7B%0A  return arr.filter(function (el) %7B%0A    return predicates.every(function (predicate) %7B%0A      return predicate(el)%0A    %7D)%0A  %7D)%0A%7D%0A%0Afunction supports (type) %7B%0A  // if type is not specified, pass through%0A  if (!type) %7B%0A    return function () %7B return true %7D%0A  %7D%0A%0A
 %0A  if
+ 
 (typ
@@ -1023,24 +1023,43 @@
 pg')
-%7B
+ %7B%0A    
 type
-=
+ = 
 'jpeg'
+%0A  
 %7D%0A
+%0A
   
+return 
 func
@@ -1077,18 +1077,22 @@
 tsType(s
-vc
+ervice
 ) %7B%0A    
@@ -1100,19 +1100,31 @@
  return 
-svc
+type && service
 .support
@@ -1152,41 +1152,8 @@
   %7D%0A
-  return arr.filter(supportsType)
 %0A%7D%0A%0A
@@ -1165,23 +1165,25 @@
 ion 
-o
+isO
 nline
-Only (svc
+ (service
 ) %7B%0A
@@ -1198,10 +1198,14 @@
 rn s
-vc
+ervice
 .onl

refactor filters