homework0/main.js
2025-02-17 22:06:53 +09:00

60 lines
1.7 KiB
JavaScript

/*
DI311 Homework 0
Author: Your name (KAIST ID)
*/
/**
*
* @param {number} start - a single integer representing the start time
* @param {number} end - a single integer representing the end time
* @returns a string in the format HH:MM:SS which will be displayed
*/
function computeDifference(start, end) {
// TODO: fill up the content on this function
console.log(start, end); // PLACEHOLDER CODE - see your input in the console
return 'HH:MM:SS'; // PLACEHOLDER CODE - returns a string
}
// DO NOT CHANGE THE CODE BELOW THIS LINE
// Call this function to show the error message (if visible is true)
function showError(visible) {
if (visible) document.querySelector('#message').removeAttribute('hidden');
else document.querySelector('#message').setAttribute('hidden', '');
}
function setResult(res) {
document.querySelector('#result').innerHTML = res;
}
function validate(hhmmss) {
const regex = /^[0-2][0-9][0-5][0-9][0-5][0-9]$/;
if (hhmmss.match(regex) === null) throw new Error('Invalid input');
return parseInt(hhmmss);
}
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('input[type="text"]').forEach((elem) => {
elem.addEventListener('input', function () {
let startTime = document.querySelector('#startTime').value;
let endTime = document.querySelector('#endTime').value;
try {
startTime = validate(startTime);
endTime = validate(endTime);
showError(false);
} catch (e) {
startTime = 0;
endTime = 0;
showError(true);
}
const diff = computeDifference(startTime, endTime);
if (diff) setResult(diff);
else showError(true);
});
});
});
export { computeDifference };