Skip to content

Instantly share code, notes, and snippets.

@mustafakirimli
Last active November 24, 2017 10:32
Show Gist options
  • Save mustafakirimli/120be1d8f5692da92a662066ae9269c9 to your computer and use it in GitHub Desktop.
Save mustafakirimli/120be1d8f5692da92a662066ae9269c9 to your computer and use it in GitHub Desktop.
var CoinStats = (function () {
var coin_data;
var debug_mode = false;
function clog(message){
if( debug_mode == true ){
console.log(message);
}
}
function _browser( url ){
clog( "XMLHttpRequest is running" );
var request = new XMLHttpRequest();
request.open('GET', url, false);
request.send(null);
return request.responseText;
}
function _UrlFetchApp( url ){
clog( "UrlFetchApp is running" );
var response = UrlFetchApp.fetch( url );
var data = response.getContentText();
return data;
}
function detectAndFetch( url ){
clog( "deciding which method gonna run UrlFetchApp or XMLHttpRequest" );
if (typeof UrlFetchApp === "undefined" ) {
return _browser(url);
}else{
return _UrlFetchApp(url);
}
}
function fetchCoinStats() {
var furl = "https://api.coinmarketcap.com/v1/ticker/?limit=250";
clog( "fetching coin stats from " + furl );
data = detectAndFetch( furl );
clog( "data has fetched, converting to json " + data );
json_data = JSON.parse(data);
clog( "transforming array of coin stats to key value object" );
coin_data = transformCoinData(json_data);
clog( "returning coin stats in json symbol=>price format " + JSON.stringify(coin_data) );
}
function transformCoinData( json_data ){
var result = json_data.reduce(function(map, obj) {
map[obj.symbol] = obj.price_usd;
return map;
}, {});
return result;
}
function getCoinData(){
if ( !coin_data ) {
clog( "coin_data has no value, calling fetchCoinStats" );
fetchCoinStats();
}
return coin_data;
}
var public = {
getCoinStats: function () {
return getCoinData();
},
getCoinPrice: function ( name ){
getCoinData();
clog( "returning coin price for " + name );
return coin_data[name];
}
};
return public;
})();
CoinStats.getCoinPrice("BTC");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment