Skip to content

Instantly share code, notes, and snippets.

@nfabian13
Last active October 1, 2015 08:01
Show Gist options
  • Save nfabian13/3917a28049cc6015899d to your computer and use it in GitHub Desktop.
Save nfabian13/3917a28049cc6015899d to your computer and use it in GitHub Desktop.
this is the code to display a bitcoin price every 10 senconds and calculate the average of the last 5 prices retrieved from the HTTP resource.
let BitcoinPrices = [];
$(document).ready(function() {
let priceIntervalStream = Rx.Observable.interval(1000).flatMap( param => {
$('#cdDiv').html(param);
return getPriceStream();
});
priceIntervalStream.subscribe( x => {
$('#lbl-price').html(x.data.total.amount);
BitcoinPrices.push(x.data.total.amount);
if(BitcoinPrices.length >= 5){
displayAvg();
}
});
});
function getPriceStream() {
return $.getJSONAsObservable("/getcurrentprice").select( d => { return d; });
}
function intervalStream() {
return Rx.Observable.generateWithRelativeTime(
10, //initialstate
x => { return x >= 0; }, //condition
x => { return x - 1; }, //iterate
x => { return x; }, //resultSelector
x => { return 1000; } //timeSelector
);
}
function displayAvg()
{
let sum = 0;
let avg = 0;
let source = Rx.Observable.fromArray(BitcoinPrices).map((value, index, obs) =>
{
//return only the latest 5 array values.
if( index > Math.abs(BitcoinPrices.length - 5) ){
return value;
}else{
return 0;
}
});
let subscription = source.subscribe( x => sum += parseFloat(x) );
avg = sum / 5;
$('#avgValue').html(avg.toFixed(2));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment