Advertisement
kstoyanov

03. Survey Parser js exam

Aug 6th, 2020
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(args) {
  2.   const surveyRegex = /<svg>((.|\n)*?)<\/svg>/g;
  3.   const format = /<cat><text>((.|\n)*)\[((.|\n)*)]((.|\n)*)<\/text><\/cat>\s*<cat>((.|\n)*)<\/cat>/g;
  4.   const valuesRegex = /\s*<g><val>([0-9]+)<\/val>([0-9]+)<\/g>/g;
  5.   let matches = surveyRegex.exec(args);
  6.   const validMatches = [];
  7.   let survey = '';
  8.   let values = '';
  9.  
  10.   if (matches) {
  11.     while (matches) {
  12.       const match = matches[1];
  13.       const isValid = format.exec(match);
  14.       if (isValid) {
  15.         validMatches.push(match);      
  16.         survey = isValid[3];
  17.         values = isValid[7];
  18.       }
  19.       matches = surveyRegex.exec(args);
  20.     }
  21.  
  22.     if (validMatches.length > 0) {
  23.       let sum = 0;
  24.       let votes = 0;
  25.       let valuesMatches = valuesRegex.exec(values);
  26.       while (valuesMatches) {
  27.         const value = Number(valuesMatches[1]);
  28.         const count = Number(valuesMatches[2]);
  29.         if (value > 0 && value <= 10) {
  30.           sum += value * count;
  31.           votes += count;
  32.           valuesMatches = valuesRegex.exec(values);
  33.         }
  34.       }
  35.  
  36.       let average = parseFloat((sum / votes).toFixed(2));
  37.       if (votes === 0) {
  38.         average = 0;
  39.       }
  40.       console.log(`${survey}: ${average}`);
  41.     } else {
  42.       console.log('Invalid format');
  43.     }
  44.   } else {
  45.     console.log('No survey found');
  46.   }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement