Skip to content

Instantly share code, notes, and snippets.

@sgromkov
Last active March 6, 2020 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgromkov/f98b88ff8be4c6fb1721292bbaab87b4 to your computer and use it in GitHub Desktop.
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
/**
* 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('.');
}
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