JSFiddle - React, Tailwind, and code Playground

by billybraga

JavaScript

function setShiftDuration(shift) {
	shift.duration = 0;
  var shiftRegex = /(\d{1,2})(H?(\d{2})?)?(A|P)?/gi;
  var getTime = function () {
  	var result = shiftRegex.exec(shift.ShiftCode);
    
    if (!result || !result[1]) {
    	console.warn("[Get Shift Duration] regex not matched");
    	return;
    }
    
    console.log("[Get Shift Duration] regex matched");
      
  	var hours = parseInt(result[1]);
    
    if (result[3]) {
    	// minutes
    	hours += parseInt(result[3]) / 60;
    }
    
    if (result[4] == "P") {
    	hours += 12; // PM
    }
    
    console.log("[Get Shift Duration] " + hours);
    
    return hours;
  };
  
  var start = getTime();
  var end = getTime();
  
  if (!start || !end) {
  	if (!start) {
    	console.warn("[Get Shift Duration] start not defined");
    }
  	
    if (!end) {
    	console.warn("[Get Shift Duration] end not defined");
    }
    
  	return;
  }
  
  // cache value
  shift.duration = end - start;

  if (shift.duration < 0) {
    shift.duration += 24;
  }
    
  return Math.round(shift.duration * 100) / 100;
}

function test(shiftCode, expected) {
  var shift = { ShiftCode: shiftCode };
  setShiftDuration(shift);
  
  if (shift.duration != expected) {
  	document.body.innerHTML += shift.ShiftCode + " = " + shift.duration + "<br />";
  } else {
  	document.body.innerHTML += "ok<br />";
  }
}

function test1() {
	test("0800-1600", 8);
	test("7P-6A", 11);
	test("7h30P-6A", 10.5);
	test("0800-1640", 16 + 40/60 - 8);
}

test1();