Skip to content

Instantly share code, notes, and snippets.

@xphere
Created September 27, 2013 08:46
Show Gist options
  • Save xphere/6725814 to your computer and use it in GitHub Desktop.
Save xphere/6725814 to your computer and use it in GitHub Desktop.
Fiddling with FRP and BaconJS
<input id="search" type="text" />
<h1>Results for search <span id="query">--</span></h1>
<ul id="results" />
var inputs = $('#search')
.asEventStream('keyup change')
.map(function(event) { return event.target.value; })
.filter(function(value) { return value.length > 2; });
var throttled = inputs.throttle(500 /* ms */);
var distinct = throttled.skipDuplicates();
var suggestions = distinct.flatMapLatest(function(value) {
return Bacon.fromPromise(searchWikipedia(value));
})
.filter(function(data) {
return data.results && data.results.length > 0;
});
var query = suggestions.map(function(data) {
return data.query;
}).toProperty('--');
query.assign($('#query'), 'text');
suggestions.onValue(function(data) {
var $results = $('#results').empty();
data.results.forEach(function(s) {
$('<li>').text(s).appendTo($results);
});
});
function searchWikipedia(term) {
var url = '//en.wikipedia.org/w/api.php?callback=?';
return $.getJSON(url, {
action: 'opensearch',
format: 'json',
search: term
})
.then(function(data) {
return { query: data[0], results: data[1] };
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment