// Licensed Materials - Property of IBM
//
// IBM Watson Analytics
//
// (C) Copyright IBM Corp. 2018
//
// US Government Users Restricted Rights - Use, duplication or
// disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
module.exports = ( function( Format )
{
"use strict";
/**
* These classes are NOT a polyfill, and are not meant to be!
* They provide a poor man's fallback for the Intl formatters, for non-compliant environments.
*/
var reCurrencyCode = /^[A-Z]{3}$/;
var nbsp = String.fromCharCode( 160 );
/**
* Object that parses an Options object and normalizes it to options.
* @class module:barejs/polyfill/Intl.NumberFormat~NumberFormatOptions
*/
function NumberFormatOptions( _options )
{
// MinimumFractionDigits is usually 0
this.minimumFractionDigits = 0;
this.maximumFractionDigits = 3;
this.minimumIntegerDigits = 1;
this.numberingSystem = "latn";
this.useGrouping = true;
switch ( "style" in _options ? _options.style : "decimal" )
{
case "percent":
this.style = "percent";
this.maximumFractionDigits = Math.max( 0, this.minimumFractionDigits );
break;
case "currency":
this.style = "currency";
if ( !_options.currency )
throw new TypeError( "Currency code is required with currency style." );
if ( ( typeof _options.currency !== "string" ) || !reCurrencyCode.test( _options.currency ) )
throw new TypeError( "Invalid currency code:" + _options.currency );
this.currency = _options.currency;
this.currencyDisplay = "code"; // This is all the fallback supports!
this.maximumFractionDigits = Math.max( 2, this.minimumFractionDigits );
break;
case "decimal":
this.style = "decimal";
break;
default:
throw new RangeError( "Value " + _options.style + " out of range for numberformat options property style" );
}
}
/**
* Provides number formatting
* @class module:barejs/polyfill/Intl.NumberFormat
* @extends module:barejs/polyfill/Intl~Format
*/
function NumberFormat( _locales, _options )
{
Format.call( this, _locales, new NumberFormatOptions( Object( _options ) ) );
}
NumberFormat.prototype = Object.create( Format.prototype,
/** @lends module:barejs/polyfill/Intl.NumberFormat# */
{
constructor: { writable: true, value: NumberFormat },
format:
{
enumerable: true,
value: function format( _value )
{
if ( _value === null || typeof _value === "undefined" )
return "";
var value = +_value;
var prefix = "";
var suffix = "";
if ( isNaN( value ) )
return "NaN";
switch( this._options.style )
{
case "percent":
value *= 100;
suffix = "%";
break;
case "currency":
prefix = this._options.currency + nbsp;
break;
}
// We're currently ignoring min/max decimal places (which is bad).
return prefix + value.toLocaleString() + suffix;
}
}
} );
return NumberFormat;
}( require( "./Format" ) ) );