Javascript Interview Question String Add Two Time Strings

Introduction

Given input of 2 strings each representing time in standard format, return the sum of the two time in standard format

Examples:// w  ww. j  a v a  2  s .  co  m
timeAddition('01:30 am', '04:30 pm') should return '06:00 pm'
timeAddition('11:22 am', '11:22 pm') should return '10:44 am'

var line = '****************************************************************';
var passed = 0;
var failed = 0;

console.log(line);
console.log('timeAddition UNIT TESTS');
console.log(line);

if ( timeAddition('01:30 am', '04:30 pm') === '06:00 pm') {
    console.log("Test 1 pass, timeAddition('01:30 am', '04:30 pm') returns '06:00 pm'");
    passed += 1;
} else {
    console.log("Test 1 failed, timeAddition('01:30 am', '04:30 pm') should return '06:00 pm'");
    failed += 1;
}

if ( timeAddition('11:22 am', '11:22 pm') === '10:44 am') {
    console.log("Test 2 pass, timeAddition('11:22 am', '11:22 pm') returns '10:44 am'");
    passed += 1;
} else {
    console.log("Test 2 failed, timeAddition('11:22 am', '11:22 pm') should return '10:44 am'");
    failed += 1;
}

console.log(line);
console.log('TOTAL TESTS PASSED: ' + passed );
console.log('TOTAL TESTS FAILED: ' + failed );
console.log(line);




function timeAddition(time1, time2) {
    var militaryTime1 = toMilitaryTime(time1);
    var militaryTime2 = toMilitaryTime(time2);
    var hour1 = Number(militaryTime1.slice(0, 2));
    var hour2 = Number(militaryTime2.slice(0, 2));
    var minute1 = Number(militaryTime1.slice(3));
    var minute2 = Number(militaryTime2.slice(3));
    var hourSum = hour1 + hour2;
    var minuteSum = minute1 + minute2;

    if (minuteSum >= 60) {
        hourSum += 1;
        minuteSum -= 60;
    }

    if (hourSum >= 24) {
        hourSum -= 24;
    }

    var militaryTimeSum = displayDoubleDigit(hourSum) + ':' + displayDoubleDigit(minuteSum);

    return toStandardTime(militaryTimeSum);
}

var line = '****************************************************************';
var passed = 0;
var failed = 0;

console.log(line);
console.log('timeAddition UNIT TESTS');
console.log(line);

if ( timeAddition('01:30 am', '04:30 pm') === '06:00 pm') {
    console.log("Test 1 pass, timeAddition('01:30 am', '04:30 pm') returns '06:00 pm'");
    passed += 1;
} else {
    console.log("Test 1 failed, timeAddition('01:30 am', '04:30 pm') should return '06:00 pm'");
    failed += 1;
}

if ( timeAddition('11:22 am', '11:22 pm') === '10:44 am') {
    console.log("Test 2 pass, timeAddition('11:22 am', '11:22 pm') returns '10:44 am'");
    passed += 1;
} else {
    console.log("Test 2 failed, timeAddition('11:22 am', '11:22 pm') should return '10:44 am'");
    failed += 1;
}

console.log(line);
console.log('TOTAL TESTS PASSED: ' + passed );
console.log('TOTAL TESTS FAILED: ' + failed );
console.log(line);



PreviousNext

Related