total domain counts

by Augustus Yuan

JavaScript

// Lets say we have a list of domains and we wanted total counts for eahc of them. Each domain and subdomain should be counted as part of the domain.

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 = [];
    for (let j=splitDomains.length - 1; j >= 0; j--) {
      
      var currentPartOfDomain = splitDomains[j]; // com ... // google
      
      
      if (j === splitDomains.length - 1) {
        keys.push(currentPartOfDomain);
      } else {
        // google 
        var joinedDomain = splitDomains.slice(j).join('.');
        keys.push(joinedDomain);
      }
      
    }
    totalCountsByDomain = addTotalCounts(totalCountsByDomain, keys, count);
  }
  return totalCountsByDomain;
}


function addTotalCounts(totalCountsByDomain, keys, count) {
  keys.forEach(function(key) {
    if (!totalCountsByDomain[key]) {
        totalCountsByDomain[key] = parseInt(count, 10);
    } else {
        totalCountsByDomain[key] += parseInt(count, 10);
    }
  });
  return totalCountsByDomain;
}

console.log(JSON.stringify(getTotalsByDomain(counts)));