Created
March 11, 2011 01:09
-
-
Save jcoglan/865294 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
JSCLASS_PATH = 'build/min'; | |
require('./' + JSCLASS_PATH + '/loader'); | |
JS.require('JS.Deferrable'); | |
Promise = new JS.Class({ | |
include: JS.Deferrable, | |
initialize: function(value) { | |
if (value !== undefined) this.succeed(value); | |
} | |
}); | |
var fs = require('fs'), | |
url = require('url'), | |
http = require('http'), | |
sys = require('sys'); | |
// pipe :: m a -> [a -> m b] -> m b | |
var pipe = function(x, functions) { | |
for (var i = 0, n = functions.length; i < n; i++) { | |
x = bind(x, functions[i]); | |
} | |
return x; | |
}; | |
// unit :: a -> Promise a | |
var unit = function(x) { | |
return new Promise(x); | |
}; | |
// bind :: Promise a -> (a -> Promise b) -> Promise b | |
var bind = function(input, f) { | |
var output = new Promise(); | |
input.callback(function(x) { | |
f(x).callback(function(y) { | |
output.succeed(y); | |
}); | |
}); | |
return output; | |
}; | |
// readFile :: String -> Promise String | |
var readFile = function(path) { | |
var promise = new Promise(); | |
fs.readFile(path, function(err, content) { | |
promise.succeed(content); | |
}); | |
return promise; | |
}; | |
// getUrl :: String -> Promise URI | |
var getUrl = function(json) { | |
var uri = url.parse(JSON.parse(json).url); | |
return new Promise(uri); | |
}; | |
// httpGet :: URI -> Promise Response | |
var httpGet = function(uri) { | |
var client = http.createClient(80, uri.hostname), | |
request = client.request('GET', uri.pathname, {'Host': uri.hostname}), | |
promise = new Promise(); | |
request.addListener('response', function(response) { | |
promise.succeed(response); | |
}); | |
request.end(); | |
return promise; | |
}; | |
// responseBody :: Response -> Promise String | |
var responseBody = function(response) { | |
var promise = new Promise(), | |
body = ''; | |
response.addListener('data', function(c) { body += c }); | |
response.addListener('end', function() { | |
promise.succeed(body); | |
}); | |
return promise; | |
}; | |
// print :: String -> Promise null | |
var print = function(string) { | |
return new Promise(sys.puts(string)); | |
}; | |
pipe(unit(__dirname + '/urls.json'), | |
[ readFile, | |
getUrl, | |
httpGet, | |
responseBody, | |
print ]); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{"url":"http://github.com/api/v2/json/user/show/jcoglan"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment