Skip to content

Commit

Permalink
Clean-up and add a few more comments
Browse files Browse the repository at this point in the history
  • Loading branch information
remusao committed Oct 26, 2017
1 parent abe5217 commit 47e5798
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 8 deletions.
1 change: 0 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,6 @@ function factory(options) {

return {
extractHostname: _extractHostname,
isIp: isIp,
isValid: isValid,
parse: parse,
tldExists: function (url) {
Expand Down
24 changes: 19 additions & 5 deletions lib/clean-host.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,24 @@ var isValid = require('./is-valid.js');
var hasPrefixRE = /^(([a-z][a-z0-9+.-]*)?:)?\/\//;


// @see https://github.com/oncletom/tld.js/issues/95
function rtrim(value) {
/**
* @see https://github.com/oncletom/tld.js/issues/95
*
* @param {string} value
*/
function trimTrailingDots(value) {
if (value[value.length - 1] === '.') {
return value.substr(0, value.length - 1);
}
return value;
}


/**
* Fast check to avoid calling `trim` when not needed.
*
* @param {string} value
*/
function checkTrimmingNeeded(value) {
return (
value.length > 0 && (
Expand All @@ -39,6 +48,11 @@ function checkTrimmingNeeded(value) {
}


/**
* Fast check to avoid calling `toLowerCase` when not needed.
*
* @param {string} value
*/
function checkLowerCaseNeeded(value) {
for (var i = 0; i < value.length; i += 1) {
var code = value.charCodeAt(i);
Expand All @@ -54,7 +68,7 @@ function checkLowerCaseNeeded(value) {
module.exports = function extractHostname(value) {
// First check if `value` is already a valid hostname.
if (isValid(value)) {
return rtrim(value);
return trimTrailingDots(value);
}

var url = value;
Expand All @@ -75,7 +89,7 @@ module.exports = function extractHostname(value) {

// Try again after `url` has been transformed to lowercase and trimmed.
if ((needsLowerCase || needsTrimming) && isValid(url)) {
return rtrim(url);
return trimTrailingDots(url);
}

// Proceed with heavier url parsing to extract the hostname.
Expand All @@ -86,7 +100,7 @@ module.exports = function extractHostname(value) {
var parts = URL.parse(url, null, true);

if (parts.hostname) {
return rtrim(parts.hostname);
return trimTrailingDots(parts.hostname);
}

return null;
Expand Down
4 changes: 2 additions & 2 deletions lib/is-valid.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ function isAlpha(code) {


/**
* Check if a hostname string is valid (according to RFC
* It's usually a preliminary check before trying to use getDomain or anything else
* Check if a hostname string is valid (according to RFC). It's usually a
* preliminary check before trying to use getDomain or anything else.
*
* Beware: it does not check if the TLD exists.
*
Expand Down

0 comments on commit 47e5798

Please sign in to comment.