UNPKG

dinero.js

Version:

An immutable library to create, calculate and format monetary values.

2 lines (1 loc) 11.1 kB
'use strict';var Defaults={defaultAmount:0,defaultCurrency:"USD",defaultPrecision:2},Globals={globalLocale:"en-US",globalFormat:"$0,0.00",globalRoundingMode:"HALF_EVEN",globalFormatRoundingMode:"HALF_AWAY_FROM_ZERO",globalExchangeRatesApi:{endpoint:void 0,headers:void 0,propertyPath:void 0}};function _typeof(a){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},_typeof(a)}function _toArray(a){return _arrayWithHoles(a)||_iterableToArray(a)||_unsupportedIterableToArray(a)||_nonIterableRest()}function _arrayWithHoles(a){if(Array.isArray(a))return a}function _iterableToArray(a){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(a))return Array.from(a)}function _unsupportedIterableToArray(a,b){if(a){if("string"==typeof a)return _arrayLikeToArray(a,b);var c=Object.prototype.toString.call(a).slice(8,-1);return"Object"===c&&a.constructor&&(c=a.constructor.name),"Map"===c||"Set"===c?Array.from(c):"Arguments"===c||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(c)?_arrayLikeToArray(a,b):void 0}}function _arrayLikeToArray(a,b){(null==b||b>a.length)&&(b=a.length);for(var c=0,d=Array(b);c<b;c++)d[c]=a[c];return d}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var Static={normalizePrecision:function(a){var b=a.reduce(function(c,a){return Math.max(c.getPrecision(),a.getPrecision())});return a.map(function(a){return a.getPrecision()===b?a:a.convertPrecision(b)})},minimum:function(a){var b=_toArray(a),c=b[0],d=b.slice(1),e=c;return d.forEach(function(a){e=e.lessThan(a)?e:a}),e},maximum:function(a){var b=_toArray(a),c=b[0],d=b.slice(1),e=c;return d.forEach(function(a){e=e.greaterThan(a)?e:a}),e}};function isNumeric(a){return!isNaN(parseInt(a))&&isFinite(a)}function isPercentage(a){return isNumeric(a)&&100>=a&&0<=a}function areValidRatios(a){return 0<a.length&&a.every(function(a){return 0<=a})&&a.some(function(a){return 0<a})}function isEven(a){return 0==a%2}function isFloat(a){return isNumeric(a)&&!Number.isInteger(a)}function countFractionDigits(){var a=0<arguments.length&&arguments[0]!==void 0?arguments[0]:0,b=a.toString();if(0<b.indexOf("e-"))return parseInt(b.split("e-")[1]);var c=b.split(".")[1];return c?c.length:0}function isHalf(a){return .5==Math.abs(a)%1}function getJSON(a){var b=1<arguments.length&&arguments[1]!==void 0?arguments[1]:{};return new Promise(function(c,d){var e=Object.assign(new XMLHttpRequest,{onreadystatechange:function(){4===e.readyState&&(200<=e.status&&400>e.status?c(JSON.parse(e.responseText)):d(new Error(e.statusText)))},onerror:function(){d(new Error("Network error"))}});e.open("GET",a,!0),setXHRHeaders(e,b.headers),e.send()})}function setXHRHeaders(a){var b=1<arguments.length&&arguments[1]!==void 0?arguments[1]:{};for(var c in b)a.setRequestHeader(c,b[c]);return a}function isUndefined(a){return"undefined"==typeof a}function flattenObject(a){var b=1<arguments.length&&void 0!==arguments[1]?arguments[1]:".",c={};return Object.entries(a).forEach(function(a){if("object"===_typeof(a[1])){var d=flattenObject(a[1]);Object.entries(d).forEach(function(d){c[a[0]+b+d[0]]=d[1]})}else c[a[0]]=a[1]}),c}function isThenable(a){return!!a&&("object"===_typeof(a)||"function"==typeof a)&&"function"==typeof a.then}function Calculator(){var a=Math.sign,b=Math.floor,c=Math.round,d=Math.abs,e=function(d,a){var b=function(a){return Math.pow(10,countFractionDigits(a))},e=Math.max(b(d),b(a));return c(d*e)*c(a*e)/(e*e)},f={HALF_ODD:function(a){var b=c(a);return isHalf(a)?isEven(b)?b-1:b:b},HALF_EVEN:function(a){var b=c(a);return isHalf(a)?isEven(b)?b:b-1:b},HALF_UP:function(a){return c(a)},HALF_DOWN:function(a){return isHalf(a)?b(a):c(a)},HALF_TOWARDS_ZERO:function(e){return isHalf(e)?a(e)*b(d(e)):c(e)},HALF_AWAY_FROM_ZERO:function(b){return isHalf(b)?a(b)*Math.ceil(d(b)):c(b)},DOWN:function(a){return b(a)}};return{add:function(c,a){return c+a},subtract:function(c,a){return c-a},multiply:function(c,a){return isFloat(c)||isFloat(a)?e(c,a):c*a},divide:function(c,a){return c/a},modulo:function(c,a){return c%a},round:function(a){var b=1<arguments.length&&arguments[1]!==void 0?arguments[1]:"HALF_EVEN";return f[b](a)}}}var calculator=Calculator();function Format(a){var b=/^(?:(\$|USD)?0(?:(,)0)?(\.)?(0+)?|0(?:(,)0)?(\.)?(0+)?\s?(dollar)?)$/gm.exec(a);return{getMatches:function(){return null===b?[]:b.slice(1).filter(function(a){return!isUndefined(a)})},getMinimumFractionDigits:function(){var a=function(a){return"."===a};return isUndefined(this.getMatches().find(a))?0:this.getMatches()[calculator.add(this.getMatches().findIndex(a),1)].split("").length},getCurrencyDisplay:function(){return{USD:"code",dollar:"name",$:"symbol"}[this.getMatches().find(function(a){return"USD"===a||"dollar"===a||"$"===a})]},getStyle:function(){return isUndefined(this.getCurrencyDisplay(this.getMatches()))?"decimal":"currency"},getUseGrouping:function(){return!isUndefined(this.getMatches().find(function(a){return","===a}))}}}function CurrencyConverter(a){var b=function(){var a=0<arguments.length&&arguments[0]!==void 0?arguments[0]:"",b=1<arguments.length?arguments[1]:void 0;for(var c in b)a=a.replace("{{".concat(c,"}}"),b[c]);return a},c=function(c,d){return getJSON(b(a.endpoint,{from:c,to:d}),{headers:a.headers})};return{getExchangeRate:function(d,e){return(isThenable(a.endpoint)?a.endpoint:c(d,e)).then(function(c){return flattenObject(c)[b(a.propertyPath,{from:d,to:e})]})}}}function assert(a,b){var c=2<arguments.length&&arguments[2]!==void 0?arguments[2]:Error;if(!a)throw new c(b)}function assertPercentage(a){assert(isPercentage(a),"You must provide a numeric value between 0 and 100.",RangeError)}function assertValidRatios(a){assert(areValidRatios(a),"You must provide a non-empty array of numeric values greater than 0.",TypeError)}function assertInteger(a){assert(Number.isInteger(a),"You must provide an integer.",TypeError)}var calculator$1=Calculator(),Dinero=function a(b){var c=Math.floor,d=Math.pow,e=Object.assign({},{amount:a.defaultAmount,currency:a.defaultCurrency,precision:a.defaultPrecision},b),f=e.amount,g=e.currency,h=e.precision;assertInteger(f),assertInteger(h);var i=a.globalLocale,j=a.globalFormat,k=a.globalRoundingMode,l=a.globalFormatRoundingMode,m=Object.assign({},a.globalExchangeRatesApi),n=function(b){var c=Object.assign({},Object.assign({},{amount:f,currency:g,precision:h},b),Object.assign({},{locale:this.locale},b));return Object.assign(a({amount:c.amount,currency:c.currency,precision:c.precision}),{locale:c.locale})},o=function(a){assert(this.hasSameCurrency(a),"You must provide a Dinero instance with the same currency.",TypeError)};return{getAmount:function(){return f},getCurrency:function(){return g},getLocale:function(){return this.locale||i},setLocale:function(a){return n.call(this,{locale:a})},getPrecision:function(){return h},convertPrecision:function(a){var b=1<arguments.length&&void 0!==arguments[1]?arguments[1]:l;return assertInteger(a),n.call(this,{amount:calculator$1.round(calculator$1.multiply(this.getAmount(),d(10,calculator$1.subtract(a,this.getPrecision()))),b),precision:a})},add:function(b){o.call(this,b);var c=a.normalizePrecision([this,b]);return n.call(this,{amount:calculator$1.add(c[0].getAmount(),c[1].getAmount()),precision:c[0].getPrecision()})},subtract:function(b){o.call(this,b);var c=a.normalizePrecision([this,b]);return n.call(this,{amount:calculator$1.subtract(c[0].getAmount(),c[1].getAmount()),precision:c[0].getPrecision()})},multiply:function(a){var b=1<arguments.length&&arguments[1]!==void 0?arguments[1]:k;return n.call(this,{amount:calculator$1.round(calculator$1.multiply(this.getAmount(),a),b)})},divide:function(a){var b=1<arguments.length&&arguments[1]!==void 0?arguments[1]:k;return n.call(this,{amount:calculator$1.round(calculator$1.divide(this.getAmount(),a),b)})},percentage:function(a){return assertPercentage(a),this.multiply(calculator$1.divide(a,100))},allocate:function(a){var b=this;assertValidRatios(a);for(var d=a.reduce(function(c,a){return calculator$1.add(c,a)}),e=this.getAmount(),f=a.map(function(a){var f=c(calculator$1.divide(calculator$1.multiply(b.getAmount(),a),d));return e=calculator$1.subtract(e,f),n.call(b,{amount:f})}),g=0;0<e;)0<a[g]&&(f[g]=f[g].add(n.call(this,{amount:1})),e=calculator$1.subtract(e,1)),g+=1;return f},convert:function(a){var b=this,c=1<arguments.length&&arguments[1]!==void 0?arguments[1]:{},d=c.endpoint,e=void 0===d?m.endpoint:d,f=c.propertyPath,g=void 0===f?m.propertyPath||"rates.{{to}}":f,h=c.headers,i=void 0===h?m.headers:h,j=c.roundingMode,l=void 0===j?k:j,o=Object.assign({},{endpoint:e,propertyPath:g,headers:i,roundingMode:l});return CurrencyConverter(o).getExchangeRate(this.getCurrency(),a).then(function(c){return assert(!isUndefined(c),"No rate was found for the destination currency \"".concat(a,"\"."),TypeError),n.call(b,{amount:calculator$1.round(calculator$1.multiply(b.getAmount(),parseFloat(c)),o.roundingMode),currency:a})})},equalsTo:function(a){return this.hasSameAmount(a)&&this.hasSameCurrency(a)},lessThan:function(b){o.call(this,b);var c=a.normalizePrecision([this,b]);return c[0].getAmount()<c[1].getAmount()},lessThanOrEqual:function(b){o.call(this,b);var c=a.normalizePrecision([this,b]);return c[0].getAmount()<=c[1].getAmount()},greaterThan:function(b){o.call(this,b);var c=a.normalizePrecision([this,b]);return c[0].getAmount()>c[1].getAmount()},greaterThanOrEqual:function(b){o.call(this,b);var c=a.normalizePrecision([this,b]);return c[0].getAmount()>=c[1].getAmount()},isZero:function(){return 0===this.getAmount()},isPositive:function(){return 0<=this.getAmount()},isNegative:function(){return 0>this.getAmount()},hasSubUnits:function(){return 0!==calculator$1.modulo(this.getAmount(),d(10,h))},hasCents:function(){return 0!==calculator$1.modulo(this.getAmount(),d(10,h))},hasSameCurrency:function(a){return this.getCurrency()===a.getCurrency()},hasSameAmount:function(b){var c=a.normalizePrecision([this,b]);return c[0].getAmount()===c[1].getAmount()},toFormat:function(){var a=0<arguments.length&&arguments[0]!==void 0?arguments[0]:j,b=1<arguments.length&&arguments[1]!==void 0?arguments[1]:l,c=Format(a);return this.toRoundedUnit(c.getMinimumFractionDigits(),b).toLocaleString(this.getLocale(),{currencyDisplay:c.getCurrencyDisplay(),useGrouping:c.getUseGrouping(),minimumFractionDigits:c.getMinimumFractionDigits(),style:c.getStyle(),currency:this.getCurrency()})},toUnit:function(){return calculator$1.divide(this.getAmount(),d(10,h))},toRoundedUnit:function(a){var b=1<arguments.length&&arguments[1]!==void 0?arguments[1]:l,c=d(10,a);return calculator$1.divide(calculator$1.round(calculator$1.multiply(this.toUnit(),c),b),c)},toObject:function(){return{amount:f,currency:g,precision:h}},toJSON:function(){return this.toObject()}}},dinero=Object.assign(Dinero,Defaults,Globals,Static);module.exports=dinero;