return false;
};
-export const convertToDate = (
- value: Date | string | number | null | undefined,
-): Date | null | undefined => {
+export const convertToDate = (value: Date | string | number | undefined): Date | undefined => {
if (isNullOrUndefined(value)) {
- return value as null | undefined;
+ return value as undefined;
}
if (isDate(value)) {
return value as Date;
}
if (isString(value) || typeof value === 'number') {
- value = new Date(value as string | number);
- if (isNaN(value.getTime())) {
- throw new Error(`Cannot convert to date: ${String(value)}`);
+ const valueToDate = new Date(value as string | number);
+ if (isNaN(valueToDate.getTime())) {
+ throw new Error(`Cannot convert to date: '${value as string | number}'`);
}
- return value;
+ return valueToDate;
}
- return null;
};
export const convertToInt = (value: unknown): number => {
changedValue = parseInt(value as string);
}
if (isNaN(changedValue)) {
- throw new Error(`Cannot convert to integer: ${String(value)}`);
+ throw new Error(`Cannot convert to integer: '${String(value)}'`);
}
return changedValue;
};
changedValue = parseFloat(value as string);
}
if (isNaN(changedValue)) {
- throw new Error(`Cannot convert to float: ${String(value)}`);
+ throw new Error(`Cannot convert to float: '${String(value)}'`);
}
return changedValue;
};
-import { hoursToMilliseconds, hoursToSeconds, isValid } from 'date-fns';
+import { hoursToMilliseconds, hoursToSeconds } from 'date-fns';
import { expect } from 'expect';
import { Constants } from '../../src/utils/Constants';
it('Verify convertToDate()', () => {
expect(convertToDate(undefined)).toBe(undefined);
- expect(convertToDate(null)).toBe(null);
- expect(isValid(convertToDate(''))).toBe(false);
+ expect(() => convertToDate('')).toThrowError(new Error("Cannot convert to date: ''"));
+ expect(() => convertToDate('00:70:61')).toThrowError(
+ new Error("Cannot convert to date: '00:70:61'"),
+ );
+ expect(convertToDate('0')).toStrictEqual(new Date('1999-12-31T23:00:00.000Z'));
+ expect(convertToDate('-1')).toStrictEqual(new Date('2000-12-31T23:00:00.000Z'));
expect(convertToDate(0)).toStrictEqual(new Date('1970-01-01T00:00:00.000Z'));
+ expect(convertToDate(-1)).toStrictEqual(new Date('1969-12-31T23:59:59.999Z'));
const dateStr = '2020-01-01T00:00:00.000Z';
let date = convertToDate(dateStr);
expect(date).toBeInstanceOf(Date);
expect(convertToInt(1.999)).toBe(1);
expect(() => {
convertToInt('NaN');
- }).toThrow('Cannot convert to integer: NaN');
+ }).toThrow("Cannot convert to integer: 'NaN'");
});
it('Verify convertToFloat()', () => {
expect(convertToFloat(1.999)).toBe(1.999);
expect(() => {
convertToFloat('NaN');
- }).toThrow('Cannot convert to float: NaN');
+ }).toThrow("Cannot convert to float: 'NaN'");
});
it('Verify convertToBoolean()', () => {