All files / src/lib checkAllUnitsNegative.ts

100% Statements 17/17
100% Branches 6/6
100% Functions 2/2
100% Lines 16/16

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  2x 2x 2x             2x       27x 27x 27x   27x 216x 216x 16x 200x 34x       27x 5x           22x          
import type { Duration, DurationInput } from '../types';
import { negate } from '../negate';
import { parse } from '../parse';
import { UNITS } from './units';
 
/**
 * Get an indication of whether all of the non-zero units in a duration are
 * negative. If they are, return a positive representation of the duration,
 * with `isAllNegative` set to `true`.
 */
export const checkAllUnitsNegative = (duration: DurationInput): {
	isAllNegative: boolean
	maybeAbsDuration: Duration
} => {
	const parsed = parse(duration);
	let hasPositive = false;
	let hasNegative = false;
 
	UNITS.forEach((unit) => {
		const value = parsed[unit];
		if (value < 0) {
			hasNegative = true;
		} else if (value > 0) {
			hasPositive = true;
		}
	});
 
	if (hasNegative && !hasPositive) {
		return {
			isAllNegative: true,
			maybeAbsDuration: negate(parsed),
		};
	}
 
	return {
		isAllNegative: false,
		maybeAbsDuration: parsed,
	};
};