Skip to content

Commit

Permalink
feat(core): Made code-to-region mapping as early as possible
Browse files Browse the repository at this point in the history
fix #30
  • Loading branch information
grantila committed Jun 24, 2019
1 parent 79f7d3b commit 191fe9a
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 22 deletions.
17 changes: 9 additions & 8 deletions lib/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 11 additions & 14 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,26 +71,23 @@ function getValidationResult( number )

function extractRegionCode( phoneNumber )
{
if ( phoneNumber.charAt( 0 ) !== '+' || phoneNumber.length < 5 )
if ( phoneNumber.charAt( 0 ) !== '+' )
return null;

var firstOne = phoneNumber.substr( 1, 1 );
var firstTwo = phoneNumber.substr( 1, 2 );
var firstThree = phoneNumber.substr( 1, 3 );

var regionCode;

regionCode = PhoneNumber.getRegionCodeForCountryCode( firstOne );
if ( regionCode !== 'ZZ' )
return regionCode;
for ( var len = 1; len < 4; ++len )
{
if ( phoneNumber.length < len + 1 )
return null;

regionCode = PhoneNumber.getRegionCodeForCountryCode( firstTwo );
if ( regionCode !== 'ZZ' )
return regionCode;
regionCode = PhoneNumber.getRegionCodeForCountryCode(
phoneNumber.substring( 1, len + 1 )
);

regionCode = PhoneNumber.getRegionCodeForCountryCode( firstThree );
if ( regionCode !== 'ZZ' )
return regionCode;
if ( regionCode !== 'ZZ' )
return regionCode;
}

return null;
}
Expand Down
24 changes: 24 additions & 0 deletions test.in/awesome-phonenumber/should-compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,33 @@ describe( 'general', function( ) {
const pn = new PhoneNumber( '+1613 734.6759', 'CA' );
expect( pn.getRegionCode( ) ).to.equal( 'CA' );
} );

it( 'should extract region by prefix as early as possible', function( ) {
const pn1 = new PhoneNumber( '+1' );
const pn1x = new PhoneNumber( '+12' );
expect( pn1.getRegionCode( ) ).to.equal( 'US' );
expect( pn1x.getRegionCode( ) ).to.equal( 'US' );

const pn2 = new PhoneNumber( '+46' );
const pn2x = new PhoneNumber( '+467' );
expect( pn2.getRegionCode( ) ).to.equal( 'SE' );
expect( pn2x.getRegionCode( ) ).to.equal( 'SE' );

const pn3 = new PhoneNumber( '+358' );
const pn3x = new PhoneNumber( '+3587' );
expect( pn3.getRegionCode( ) ).to.equal( 'FI' );
expect( pn3x.getRegionCode( ) ).to.equal( 'FI' );
} );
} );


describe( 'errors', function( ) {
it( 'should not allow too short numbers', function( ) {
var pn = new PhoneNumber( '+12' );
expect( pn.isValid( ) ).to.be.false;
expect( pn.isPossible( ) ).to.be.false;
} );

it( 'should handle invalid country code', function( ) {
var pn = new PhoneNumber( '+0123' );
expect( pn.isValid( ) ).to.be.false;
Expand Down

0 comments on commit 191fe9a

Please sign in to comment.