/*
* Given an array of domain hits that is given in the format of
* [count,domain URL]
*
* return a map of counts for each subdomain. This includes the lowest level (com)
* and the highest level (abc.google.com). The counts should add all of them as well
*
* Example:
*
*/
var counts = [
'13,twitch.tv',
'10,help.twitch.tv',
'40,www.twitchcon.com',
'20,xyz.google.com',
'19,abc.google.com',
];
/**
* For the above, the output should be
* {"tv":23,"twitch.tv":23,"help.twitch.tv":10,"com":79,"twitchcon.com":40,"www.twitchcon.com":40,"google.com":39,"xyz.google.com":20,"abc.google.com":19}
*
* com is 79 because it includes xyz.google.com (20) and abc.google.com (19) and www.twitchcon.com (40)
* tv similarly is 23 because it includes twitch.tv and help.twitch.tv
* google.com is 39 because it adds xyz and abc as they are both under the google.com subdomain
*
* You can assume no paths are included in the URLs
*
* for run time complexity you can assume that there is a constant upperbound to the number of domains but the
* code should work for any number of domain levels
*/
function getTotalsByDomain(counts) {
let totalCountsByDomain = {};
for (let i = 0; i < counts.length; i++) {
let currentArray = counts[i].split(',');
let count = currentArray[0];
let domain = currentArray[1];
let splitDomains = domain.split('.');
var keys = [];
// traverse backwards because we care about the last part of the domain i.e. com
for (let j=splitDomains.length - 1; j >= 0; j--) {
var currentPartOfDomain = splitDomains[j]; // com ... // google
// if we are at the end, i.e. com, push that "subdomain" in
if (j === splitDomains.length - 1) {
keys.push(currentPartOfDomain);
} else {
// join the domain i.e. "google" with "com" and lets keep going
var joinedDomain = splitDomains.slice(j).join('.');
keys.push(joinedDomain);
}
}
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.