Exchange rate example – Exchange function

Before writing the exchanging function, we can design how we will use this function. This is kind of designing the API, Application Programming Interface.

For the rate exchange function, we need to take 3 parameters – the amount of money, the original currency and the target currency.

We may design our function to be used like this:

1var result = exchange(100, 'mop', 'cny');

This works without any issues. Just that the trend now is to make this type of generic API call more readable. In the other words, make it more like English. How about making the exchange rate API as follow.

English javascript exchange

1Exchange(100, 'mop').to('cny');

And the implementation:

 1// static rate as at 8 Nov, 2013 11:45am
 2var rate = {
 3    CNY: 6.100569,
 4    MOP: 8.00591,
 5    HKD: 7.751621
 6};
 7
 8function Exchange(value, srcCurrency) {
 9    var srcPerUsd = rate[srcCurrency.toUpperCase()];
10    var usdPerSrc = 1 / srcPerUsd;
11
12    return {
13        to: function(targetCurrency) {
14          var targetPerUsd = rate[targetCurrency.toUpperCase()];
15          var srcPerTarget = usdPerSrc * targetPerUsd;
16          return value * srcPerTarget;
17        }
18    };
19}

And the usage.

1Exchange(100, 'mop').to('cny')
2Exchange(100, 'hkd').to('cny')
3Exchange(100, 'usd').to('hkd')
4Exchange(100, 'hkd').to('mop')

What is the beauty of separating the exchange and to function?

Imagine an app that we can convert one currency into many different currencies.

1var cash = Exchange(100, 'mop');
2cash.to('hkd');
3cash.to('cny');
4cash.to('usd');
5cash.to('cad');

This sounds great on both reusability and readability.

What’s next? We’re going to take a look at “Exchange rate example – Full example”.

overlaied image when clicked on thumbnail

Makzan | Mobile web app dev with phonegap | Table of Content