DEV Community

Discussion on: Daily Challenge #223 - Responsible Drinking

Collapse
 
alvaromontoro profile image
Alvaro Montoro • Edited

Using regular expressions in JavaScript:

const hydrate = s => {
  // get an array with all the numbers in the string, and add the values using reduce
  const number = s.match(/\d/g)
                  .reduce((acc, val) => acc + parseInt(val), 0);
  return `${number} glass${number != 1 ? 'es' : ''} of water`;
}

We get the following results:

hydrate("1 beer")
// 1 glass of water 
hydrate("2 glasses of wine and 1 shot")
// 3 glasses of water 
hydrate("1 shot, 5 beers, 2 shots, 1 glass of wine, 1 beer")
// 10 glasses of water
Collapse
 
fluffynuts profile image
Davyd McColl

I didn't see yours, but mine is practically identical 😮

Collapse
 
alvaromontoro profile image
Alvaro Montoro

Yours has some checks that make it more robust... And that I probably should add to mine 😳