DEV Community

Discussion on: JavaScript Challenge

Collapse
 
mellen profile image
Matt Ellen
function lucky(s)
{
  // split the string into an array so that it can be reduced
  let sarr = s.split('');
  // reduce the array into a character -> count map
  let counts = sarr.reduce((acc, c) => {if(acc[c]){acc[c]++;}else{acc[c]=1;} return acc;}, {});
  let smallestCount = Number.MAX_VALUE;
  // find the smallest frequency in the map
  for(let c in counts)
  {
    if(Object.prototype.hasOwnProperty.call(counts, c) && counts[c] < smallestCount)
    {
        smallestCount = counts[c];
    }
  }
  let biggerCount = 0;
  // count how many characters exceed the smallest frequency
  for(let c in counts)
  {
    if(Object.prototype.hasOwnProperty.call(counts, c) && counts[c] > smallestCount)
    {
        biggerCount += counts[c] - smallestCount;
    }
  }

  // exceeding 0 times fullfills point 1
  let easyLucky = biggerCount == 0;
  // exceeding only once fullfills point 2
  let hardLucky = biggerCount == 1;
  // if either is true you have a lucky string
  return easyLucky || hardLucky;
}

Object.prototype.hasOwnProperty.call(counts, c) is necessary in case the prototype for object has been messed with.