all files / scripts/ads/vast/ parsers.js

100% Statements 28/28
100% Branches 12/12
100% Functions 8/8
100% Lines 28/28
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63              94×   94× 26× 26× 23×       94×     23×     23×     23×         63× 10×   53×     63× 63×     10×                  
'use strict';
 
var utilities = require('../../utils/utilityFunctions');
 
var durationRegex = /(\d\d):(\d\d):(\d\d)(\.(\d\d\d))?/;
 
var parsers = {
 
  duration: function parseDuration(durationStr) {
 
    var match, durationInMs;
 
    if (utilities.isString(durationStr)) {
      match = durationStr.match(durationRegex);
      if (match) {
        durationInMs = parseHoursToMs(match[1]) + parseMinToMs(match[2]) + parseSecToMs(match[3]) + parseInt(match[5] || 0);
      }
    }
 
    return isNaN(durationInMs) ? null : durationInMs;
 
    /*** local functions ***/
    function parseHoursToMs(hourStr) {
      return parseInt(hourStr, 10) * 60 * 60 * 1000;
    }
 
    function parseMinToMs(minStr) {
      return parseInt(minStr, 10) * 60 * 1000;
    }
 
    function parseSecToMs(secStr) {
      return parseInt(secStr, 10) * 1000;
    }
  },
 
  offset: function parseOffset(offset, duration) {
    if(isPercentage(offset)){
      return calculatePercentage(offset, duration);
    }
    return parsers.duration(offset);
 
    /*** Local function ***/
    function isPercentage(offset) {
      var percentageRegex = /^\d+(\.\d+)?%$/g;
      return percentageRegex.test(offset);
    }
 
    function calculatePercentage(percentStr, duration) {
      if(duration) {
        return calcPercent(duration, parseFloat(percentStr.replace('%', '')));
      }
      return null;
    }
 
    function calcPercent(quantity, percent){
      return quantity * percent / 100;
    }
  }
 
};
 
 
module.exports = parsers;