mirror of
https://github.com/iib0011/omni-tools.git
synced 2025-12-10 00:48:37 -06:00
chore:
- time util file created - time validation util function implemented
This commit is contained in:
parent
b1f63a3207
commit
9d25c37f4b
58
src/utils/time.ts
Normal file
58
src/utils/time.ts
Normal file
@ -0,0 +1,58 @@
|
||||
type TimeValidationResult = {
|
||||
isValid: boolean;
|
||||
hours: number;
|
||||
minutes: number;
|
||||
seconds: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Validates human-readable time format (HH:MM or HH:MM:SS)
|
||||
* Supports either ':' or '.' as a separator, but not both
|
||||
* @param {string} input - string time format
|
||||
* * @returns {{
|
||||
* isValid: boolean, // true if the input is a valid time
|
||||
* hours: number, // parsed hours (0 or greater)
|
||||
* minutes: number, // parsed minutes (0-59)
|
||||
* seconds: number // parsed seconds (0-59, 0 if not provided)
|
||||
* }}
|
||||
*/
|
||||
export function humanTimeValidation(input: string): TimeValidationResult {
|
||||
const result = { isValid: false, hours: 0, minutes: 0, seconds: 0 };
|
||||
|
||||
if (!input) return result;
|
||||
|
||||
input = input.trim();
|
||||
|
||||
// Operator use validation
|
||||
// use of one between these two operators '.' or ':'
|
||||
|
||||
const hasColon = input.includes(':');
|
||||
const hasDot = input.includes('.');
|
||||
|
||||
if (hasColon && hasDot) return result;
|
||||
|
||||
if (!hasColon && !hasDot) return result;
|
||||
|
||||
const separator = hasColon ? ':' : '.';
|
||||
|
||||
// Time parts validation
|
||||
|
||||
const parts = input.split(separator);
|
||||
|
||||
if (parts.length < 2 || parts.length > 3) return result;
|
||||
|
||||
const [h, m, s = '0'] = parts;
|
||||
|
||||
// every character should be a digit
|
||||
if (![h, m, s].every((x) => /^\d+$/.test(x))) return result;
|
||||
|
||||
const hours = parseInt(h);
|
||||
const minutes = parseInt(m);
|
||||
const seconds = parseInt(s);
|
||||
|
||||
if (minutes < 0 || minutes > 59) return result;
|
||||
if (seconds < 0 || seconds > 59) return result;
|
||||
if (hours < 0) return result;
|
||||
|
||||
return { isValid: true, hours, minutes, seconds };
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user