All files / src toUnit.ts

100% Statements 22/22
100% Branches 0/0
100% Functions 5/5
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80  6x 6x                 6x 220x   1680x 1680x               6x       133x     6x 109x             6x           6x           6x           6x           6x               6x               6x  
import { DurationInput } from './types';
import { parse } from './parse';
import { UNITS_META, UNITS_META_MAP } from './lib/units';
 
/**
 * Convert the input value to milliseconds represented by a duration object.
 * If a number is passed this is returned verbatim as the number
 * of milliseconds.
 *
 * @example toMilliseconds({ days: 1 }) // 86400000
 */
export const toMilliseconds = (duration: DurationInput): number => {
	const parsed = parse(duration);
 
	return UNITS_META.reduce((total, { unit, milliseconds }) => {
		return total + (parsed[unit] * milliseconds);
	}, 0);
};
 
/**
 * Convert the input value to the specificed unit.
 * @example toUnit({ minutes: 2 }, 'seconds') // 120
 */
export const toUnit = (
	duration: DurationInput,
	unit: keyof typeof UNITS_META_MAP,
): number => {
	return toMilliseconds(duration) / UNITS_META_MAP[unit].milliseconds;
};
 
const createDurationConverter = (unit: keyof typeof UNITS_META_MAP) => {
	return (duration: DurationInput): number => toUnit(duration, unit);
};
 
/**
 * Convert the input value to seconds.
 * @example toSeconds({ minutes: 2 }) // 120
 */
export const toSeconds = createDurationConverter('seconds');
 
/**
 * Convert the input value to minutes.
 * @example toMinutes({ hours: 1, minutes: 10 }) // 70
 */
export const toMinutes = createDurationConverter('minutes');
 
/**
 * Convert the input value to hours.
 * @example toHours({ days: 1 }) // 24
 */
export const toHours = createDurationConverter('hours');
 
/**
 * Convert the input value to days.
 * @example toDays({ hours: 12 }) // 0.5
 */
export const toDays = createDurationConverter('days');
 
/**
 * Convert the input value to weeks.
 * @example toWeeks({ days: 14 }) // 2
 */
export const toWeeks = createDurationConverter('weeks');
 
/**
 * Convert the input value to months.
 * Note, this is a rough approximation as the length of a month is variable.
 *
 * @example toMonths({ months: 10, days: 365 }) // 11
 */
export const toMonths = createDurationConverter('months');
 
/**
 * Convert the input value to years.
 * Note, this is a rough approximation as the length of a year is variable.
 *
 * @example toYears({ years: 10, days: 365 }) // 11
 */
export const toYears = createDurationConverter('years');