DEV Community

Discussion on: JavaScript Challenge

Collapse
 
mellen profile image
Matt Ellen • Edited

Also, I just found out about Map, so here's a version that uses that 😁:

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.get(c))
                                         {
                                           acc.set(c, acc.get(c) + 1);
                                         }
                                         else
                                         {
                                           acc.set(c, 1);
                                         } 
                                         return acc;
                                       }, new Map());
  let smallestCount = Number.MAX_VALUE;
  // find the smallest frequency in the map
  counts.forEach((count, c) => {if(count < smallestCount){smallestCount = count;}});
  let biggerCount = 0;
  // count how many characters exceed the smallest frequency
  counts.forEach((count, c) => {if(count > smallestCount){biggerCount += count - 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;
}