return Utils.formatDurationMilliSeconds(duration * 1000);
}
- public static convertToDate(value: unknown): Date | null | undefined {
+ public static convertToDate(
+ value: Date | string | number | null | undefined
+ ): Date | null | undefined {
if (Utils.isNullOrUndefined(value)) {
return value as null | undefined;
}
return value;
}
if (Utils.isString(value) || typeof value === 'number') {
- return new Date(value as string | number);
+ return new Date(value);
}
return null;
}
return value as number;
}
if (typeof value === 'number') {
- changedValue = Math.trunc(value);
+ return Math.trunc(value);
}
if (Utils.isString(value)) {
changedValue = parseInt(value as string);
}
+ if (isNaN(changedValue)) {
+ throw new Error(`Cannot convert to integer: ${value.toString()}`);
+ }
return changedValue;
}
if (Utils.isString(value)) {
changedValue = parseFloat(value as string);
}
+ if (isNaN(changedValue)) {
+ throw new Error(`Cannot convert to float: ${value.toString()}`);
+ }
return changedValue;
}
if (value) {
// Check the type
if (typeof value === 'boolean') {
- result = value;
+ return value;
} else if (
Utils.isString(value) &&
((value as string).toLowerCase() === 'true' || value === '1')
const invalidDate = Utils.convertToDate('');
expect(invalidDate instanceof Date && !isNaN(invalidDate.getTime())).toBe(false);
expect(Utils.convertToDate(0)).toStrictEqual(new Date('1970-01-01T00:00:00.000Z'));
- expect(Utils.convertToDate([])).toBe(null);
- expect(Utils.convertToDate({})).toBe(null);
- expect(Utils.convertToDate(new Map())).toBe(null);
- expect(Utils.convertToDate(new Set())).toBe(null);
- expect(Utils.convertToDate(new WeakMap())).toBe(null);
- expect(Utils.convertToDate(new WeakSet())).toBe(null);
const dateStr = '2020-01-01T00:00:00.000Z';
let date = Utils.convertToDate(dateStr);
expect(date).toBeInstanceOf(Date);
expect(Utils.convertToInt(1.1)).toBe(1);
expect(Utils.convertToInt(1.9)).toBe(1);
expect(Utils.convertToInt(1.999)).toBe(1);
+ expect(() => {
+ Utils.convertToInt('NaN');
+ }).toThrow('Cannot convert to integer: NaN');
});
it('Verify convertToFloat()', () => {
expect(Utils.convertToFloat(1.1)).toBe(1.1);
expect(Utils.convertToFloat(1.9)).toBe(1.9);
expect(Utils.convertToFloat(1.999)).toBe(1.999);
+ expect(() => {
+ Utils.convertToFloat('NaN');
+ }).toThrow('Cannot convert to float: NaN');
});
it('Verify convertToBoolean()', () => {