Last active
December 19, 2015 17:39
-
-
Save srikumarks/5992608 to your computer and use it in GitHub Desktop.
CSP demo 2 - Rob Pike's example
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
<button id="search">Search</button> | |
<div id="results"></div> | |
<script src="IO.js"></script> | |
<script src="IO.Browser.js"></script> | |
<script> | |
var fake_search = function (kind) { | |
return function (query) { | |
return IO.do([ | |
function (_) { | |
return IO.delay(Math.floor(Math.random() * 100)); | |
}, | |
IO.supply({kind: kind, query: query}) | |
]); | |
}; | |
}; | |
var web1 = fake_search('web1'), | |
web2 = fake_search('web2'), | |
image1 = fake_search('image1'), | |
image2 = fake_search('image2'), | |
video1 = fake_search('video1'), | |
video2 = fake_search('video2'); | |
var fastest = function (query, replicas) { | |
return IO.any(replicas.map(function (f) { return f(query); })); | |
}; | |
var timeoutWithMsg = function (ms, action, msg) { | |
return IO.any([action, IO.do([IO.delay(ms), IO.supply(msg)])]); | |
}; | |
var last3Results = function (arr) { return arr.length === 3; }; | |
var google = function (query, target) { | |
var collectResults = IO.atomic([IO.collectUntil(), IO.cond([[last3Results, target]], IO.pass)]); | |
var pipe = function (src) { | |
return IO.tee(IO.do([timeoutWithMsg(80, src[1], src[0] + ' timed out'), collectResults])); | |
}; | |
return IO.do([ | |
['web', fastest(query, [web1, web2])], | |
['image', fastest(query, [image1, image2])], | |
['video', fastest(query, [video1, video2])] | |
].map(pipe)); | |
}; | |
var showResults = IO.do([ | |
function (obj) { return JSON.stringify(obj); }, | |
IO.Browser.show('render', 'innerText') | |
]); | |
IO.Browser.on('search', 'click', function (_) { return google('meow', showResults); }); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment