Check exchange rates using The Console
The Console started as a small side project that was supposed to automatically perform things I do often manually. Checking exchange rates of currencies is one of amongst those repeated actions.
1. invoke: currency
First, I want to check if scripts takes enough of arguments. If not, then display the “Usage” as many shell programs do.
We’ll just evaluate boolean expression args.length != 0 . If it’s false, then assertInfo() will print text white.
assertInfo(args.length != 0,
"Usages:\n" +
" - currency 12 gbp eur\n" +
" - currency gbp eur"
)
That’s not bulletproof but let’s keep it simple for now. To achieve red text, which looks as an error, you may use assert() instead, it would look like this:
2. invoke: currency gbp eur
First, I take arguments into variables for better readability.
var amount = 1.0
var from = args[1]
var to = args[2]
Then I contact Yahoo Finance service to check exchange rate - this time between British Pound (GBP) and Euro (EUR):
var url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=' + from.toUpperCase() + to.toUpperCase() + '=X'
var data = Utils.requestUrl(url)
The server returns value in CSV format so I have to split it and take second value, then print it to the console output:
console.log(data.split(',')[1])
3. invoke: currency 175 gbp eur
To support a specific amount, i.e. - as in this case - 175, I have to check whether there’s 2 or 3 arguments.
var amount = args.length == 3 ? args[0] : 1.0
var from = args[args.length == 3 ? 1 : 0]
var to = args[args.length == 3 ? 2 : 1]<br>
Then, in the end, print exchange rate multipled by amount .
console.log(data.split(',')[1] * amount)
Put it somewhere!
Your script will be loaded if it’s anywhere inside %APPDATA%\TheConsole\scripts folder. Yeah, in the moment of writing it’s supported on Windows only but that may change in future.
Summary
The example above shows just a few API calls which cover multiple situations of analyzing data from websites. Between the API functions are:
- console.log()
- synchronous Utils.requestUrl()
- assert()
- assertInfo()
- args array
You can find more about the API on GitHub.