// 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.
( function( exports, ObjectPolyfill )
{
"use strict";
// Instead of fully validating the tag, we match any string that starts with two or three [a-z] characters,
// followed by any number of -[a-z0-9] suffixes.
var reTag = /^(i|[a-zA-Z]{2,3})((?:\-[a-zA-Z0-9]+)*)$/;
var reFormat = /^[a-zA-Z]+|\-\w+/g;
function bcp47Replace( _match, _offset )
{
/*
* Formatting follows simple rules:
* > if NOT the first entry
* > Length 2: UPPER case
* > Length 4: Title case
* > lower case
* For any match that is not the first (_offset is 0), take into account '-' is in the match
*/
var len = _offset ? _match.length : 0;
return len === 3 ? // +1 for '-'
_match.toUpperCase() :
len === 5 ? // +1 for '-'
_match.substr( 0, 2 ).toUpperCase() + _match.substr( 2 ).toLowerCase() :
_match.toLowerCase();
}
function isStructurallyValidLanguageTag( _tag )
{
// With the current implementation, the type check for string is unnecessary.
return /*typeof _tag === "string" &&*/ reTag.test( _tag );
}
function canonicalizeLanguageTag( _tag )
{
// Officially this validation should be performed before calling this function,
// but with this limited implementation it's more convenient to perform it here.
var tag = String( _tag );
if ( !isStructurallyValidLanguageTag( tag ) )
throw new RangeError( "Invalid language tag: " + tag );
return tag.replace( reFormat, bcp47Replace );
}
/**
* @memberof module:barejs/polyfill/Intl
* @param {String|Array} _locales
* @return {String[]} List of canonical locale tags.
*/
exports.getCanonicalLocales = function getCanonicalLocales( _locales )
{
var seen;
if ( _locales === undefined )
{
seen = new Array( 0 );
}
else if ( typeof _locales === "string" )
{
seen = new Array( 1 );
seen[ 0 ] = canonicalizeLanguageTag( _locales );
}
else
{
seen = [];
var locales = ObjectPolyfill.toObject( _locales );
var len = locales.length || 0;
for ( var i = 0; i < len; ++i )
{
var tag = canonicalizeLanguageTag( locales[ i ] );
if ( seen.indexOf( tag ) < 0 )
seen.push( tag );
}
}
return seen;
};
}( module.exports, require( "../Object" ) ) );