From 85eed2df55c3022ac6fe7fe83911ecf2a2b8a25d Mon Sep 17 00:00:00 2001 From: Eduardo Garcia Date: Tue, 19 Mar 2013 16:22:05 -0600 Subject: [PATCH] Adds fx.pair() according to issue #4. --- money.js | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/money.js b/money.js index 1de0240..f3e32a3 100644 --- a/money.js +++ b/money.js @@ -66,6 +66,39 @@ return val * getRate( opts.to, opts.from ); }; + // Returns the exchange rate between two currencies. + // Accepts a string parameter of the form "FROM/TO", or an object with "from" and "to" properties. + var pair = fx.pair = function(currencies) { + var to, from; + + if(typeof currencies == 'object') { + // Throw an error if currencies.to or currencies.from isn't set + if(!currencies.from || !currencies.to) throw "fx error: expected an object with properties 'to' and 'from' set."; + + from = currencies.from; + to = currencies.to; + } + else if(typeof currencies == 'string') { + if(currencies.indexOf('/') == -1) { + throw "fx error: expected a string of the form FROM/TO."; + } + + currencies = currencies.split('/'); + + if(currencies.length != 2) { + throw "fx error: expected a string of the form FROM/TO."; + } + + from = currencies[0]; + to = currencies[1]; + } + else { + throw "fx error: unknown format."; + } + + return getRate(to, from); + }; + // Returns the exchange rate to `target` currency from `base` currency var getRate = function(to, from) { // Save bytes in minified version @@ -129,7 +162,6 @@ return convert(this._v, {from: this._fx ? this._fx : fx.settings.from, to: currency}); }; - /* --- Module Definition --- */ // Export the fx object for CommonJS. If being loaded as an AMD module, define it as such. @@ -163,4 +195,4 @@ } // Root will be `window` in browser or `global` on the server: -}(this)); +}(this)); \ No newline at end of file