Last active
March 6, 2020 18:49
-
-
Save sgromkov/f98b88ff8be4c6fb1721292bbaab87b4 to your computer and use it in GitHub Desktop.
Getting part of a domain name by host name. Covered by unit tests on Jest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Returns domain name's part by given hostname and level | |
* @param {string} hostname | |
* @param {Number} level | |
* @returns {string} domain name's part | |
*/ | |
export default function getDomainByHostname(hostname = "", level = 0) { | |
return hostname.split('.').slice(-level).join('.'); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import getDomainByHostname from './getDomainByHostname'; | |
describe('getDomainByHostname()', () => { | |
test('should return empty string if the hostname has not been passed', () => { | |
expect(getDomainByHostname()).toEqual(''); | |
expect(getDomainByHostname('')).toEqual(''); | |
expect(getDomainByHostname('', 1)).toEqual(''); | |
expect(getDomainByHostname('', 2)).toEqual(''); | |
}); | |
test('should return first level domain', () => { | |
expect(getDomainByHostname('com', 1)).toEqual('com'); | |
expect(getDomainByHostname('site.com', 1)).toEqual('com'); | |
expect(getDomainByHostname('third.site.com', 1)).toEqual('com'); | |
expect(getDomainByHostname('fouth.third.site.com', 1)).toEqual('com'); | |
}); | |
test('should return seconde level domain', () => { | |
expect(getDomainByHostname('site.com')).toEqual('site.com'); | |
expect(getDomainByHostname('site.com', 2)).toEqual('site.com'); | |
expect(getDomainByHostname('third.site.com', 2)).toEqual('site.com'); | |
expect(getDomainByHostname('fouth.third.site.com', 2)).toEqual('site.com'); | |
}); | |
test('should return third level domain', () => { | |
expect(getDomainByHostname('third.site.com')).toEqual('third.site.com'); | |
expect(getDomainByHostname('third.site.com', 3)).toEqual('third.site.com'); | |
expect(getDomainByHostname('fouth.third.site.com', 3)).toEqual('third.site.com'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment