All files / src/core to.ts

100% Statements 36/36
100% Branches 17/17
100% Functions 5/5
100% Lines 36/36

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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 1881x                                                                                           1x                                       1x 1x 1x                                               1x 11x 11x 11x                                       1x 7x   7x 1x 1x   6x 6x 6x 6x 6x 6x 6x 6x 6x 7x                                         1x 16x 9x   16x 1x 1x   8x 16x                                           1x 12x 12x 1x  
import { Is } from "./is";
 
/**
 * Type representing the parts of a date.
 * @typedef {Object} DatePartsType
 * @property {number} year - The year of the date.
 * @property {number} month - The month of the date (1-12).
 * @property {number} day - The day of the date (1-31).
 * @property {number} hour - The hour of the date (0-23).
 * @property {number} minute - The minute of the date (0-59).
 * @property {number} second - The second of the date (0-59).
 * @property {number} timestamp - The timestamp of the date in milliseconds.
 *
 * @example
 * ```ts
 * const dateParts: DatePartsType = {
 *   year: 2023,
 *   month: 8,
 *   day: 1,
 *   hour: 12,
 *   minute: 0,
 *   second: 0,
 *   timestamp: 1693456000000
 * };
 * console.log(dateParts); //output: { year: 2023, month: 8, day: 1, hour: 12, minute: 0, second: 0, timestamp: 1693456000000 }
 * ```
 *
 * @category Types
 */
export type DatePartsType = {
	year: number;
	month: number;
	day: number;
	hour: number;
	minute: number;
	second: number;
	timestamp: number;
};
 
/**
 * To - A collection of conversion utilities for various data types.
 *
 * @category Core
 * @class
 * @author 	Heliomar P. Marques <https://navto.me/heliomarpm>
 */
export const To = {
	/**
	 * Converts a JSON object to a Record<string, T> type.
	 *
	 * @param jsonObject The JSON object to convert.
	 * @returns A new Record<string, T> object with the same key-value pairs as the original JSON object.
	 * @template T The type defined by the input JSON object.
	 * @example
	 *
	 * ```js
	 *  import { to } from '@heliomarpm/helpers';
	 *  import jsonLanguages from './languages.json';
	 *
	 *  const languages: Record<string, string> = to.dictionary<string>(jsonLanguages);
	 *  let jsonLocale: Record<string, string>
	 *  jsonLocale = require(`locales/${navigator.language}`);
	 * ```
	 *
	 * @category To.dictionary
	 */
	dictionary<T>(jsonObject: { [key: string]: T }): Record<string, T> {
		return { ...jsonObject } as Record<string, T>;
	},
 
	/**
	 * Converts a value to a boolean, following these rules:
	 *   - Numeric values are considered `true` except for the string '0'.
	 *   - Strings that match the regular expression `/^true$/i` are considered `true`.
	 *   - All other values are considered `false`.
	 *
	 * @param value - The value to be converted to a boolean.
	 * @returns `boolean` The boolean representation of the input value.
	 *
	 * @example
	 * ```ts
	 * To.boolean(1); //output: true
	 * To.boolean('true'); //output: true
	 * To.boolean('0'); //output: false
	 * To.boolean('false'); //output: false
	 * To.boolean(null); //output: false
	 * To.boolean(undefined); //output: false
	 * To.boolean(''); //output: false
	 * ```
	 *
	 * @category To.boolean
	 */
	boolean(value: number | string): boolean {
		const str = String(value).trim().toLowerCase();
		return Is.numeric(value) ? str !== "0" : str === "true";
	},
 
	/**
	 * Extracts parts of a date such as year, month, day, etc.
	 *
	 * @param date - The date to be parsed, can be a Date object or a string.
	 * @returns An object containing year, month, day, hour, minute, second, and timestamp.
	 *
	 * @example
	 * ```ts
	 * To.dateParts(new Date()); //output: { year: 2023, month: 8, day: 1, hour: 0, minute: 0, second: 0, timestamp: 1693456000000 }
	 * To.dateParts('2023-08-01'); //output: { year: 2023, month: 8, day: 1, hour: 0, minute: 0, second: 0, timestamp: 1693456000000 }
	 * To.dateParts('2023-08-01T00:00:00'); //output: { year: 2023, month: 8, day: 1, hour: 0, minute: 0, second: 0, timestamp: 1693456000000 }
	 * To.dateParts('2023-08-01 00:00:00'); //output: { year: 2023, month: 8, day: 1, hour: 0, minute: 0, second: 0, timestamp: 1693456000000 }
	 * To.dateParts('2023-08-01 00:00:00.000'); //output: { year: 2023, month: 8, day: 1, hour: 0, minute: 0, second: 0, timestamp: 1693456000000 }
	 * To.dateParts('2023-08-01 00:00:00.000Z'); //output: { year: 2023, month: 8, day: 1, hour: 0, minute: 0, second: 0, timestamp: 1693456000000 }
	 * ```
	 *
	 * @category To.dateParts
	 */
	dateParts(date: Date | string | number): DatePartsType {
		const parsedDate = !(date instanceof Date) ? new Date(date) : date;
 
		if (Number.isNaN(parsedDate.getTime())) {
			throw new Error("Invalid date");
		}
 
		return {
			year: parsedDate.getFullYear(), // Extract year
			month: parsedDate.getMonth() + 1, // Extract month (zero-based, so add 1)
			day: parsedDate.getDate(), // Extract day
			hour: parsedDate.getHours(), // Extract hour
			minute: parsedDate.getMinutes(), // Extract minute
			second: parsedDate.getSeconds(), // Extract second
			timestamp: parsedDate.getTime(), // Extract timestamp
		};
	},
 
	/**
	 * Converts a value to a Date object.
	 *
	 * @param {Date|string|number} input - The value to be converted to a Date object.
	 * @returns {Date} The Date object representation of the input value.
	 *
	 * @example
	 * ```ts
	 * To.date(new Date()); //output: <Date>
	 * To.date(1693456000000); //output: <Date>
	 * To.date('2023-08-01'); //output: <Date>
	 * To.date('2023-08-01T00:00:00'); //output: <Date>
	 * To.date('2023-08-01 00:00:00'); //output: <Date>
	 * To.date('2023-08-01 00:00:00.000'); //output: <Date>
	 * To.date('2023-08-01 00:00:00.000Z'); //output: <Date>
	 * ```
	 *
	 * @category To.date
	 */
	date(input: Date | string | number): Date {
		if (input instanceof Date) return input;
		const date = new Date(input);
 
		if (Number.isNaN(date.getTime())) {
			throw new Error("Invalid date");
		}
 
		return date;
	},
 
	/**
	 * Converts a value to a number, following these rules:
	 *   - Numeric values are considered as-is.
	 *   - Strings that match the regular expression `/^\d+$/` are considered as numeric.
	 *   - All other values are considered `NaN`.
	 *
	 * @param value - The value to be converted to a number.
	 * @returns `number` The numeric representation of the input value.
	 *
	 * @example
	 * ```ts
	 * To.number(123); //output: 123
	 * To.number('123'); //output: 123
	 * To.number('123.45'); //output: NaN
	 * To.number('abc'); //output: NaN
	 * To.number(null); //output: NaN
	 * ```
	 *
	 * @category To.number
	 */
	number(value: unknown): number {
		return Is.numeric(value) ? Number(value) : Number.NaN;
	},
};