UNPKG

@sap_oss/wdio-qmate-service

Version:

[![REUSE status](https://api.reuse.software/badge/github.com/SAP/wdio-qmate-service)](https://api.reuse.software/info/github.com/SAP/wdio-qmate-service)[![Node.js CI](https://github.com/SAP/wdio-qmate-service/actions/workflows/node.js.yml/badge.svg)](http

306 lines 15 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Formatter = void 0; const formatter_constants_1 = require("./constants/formatter.constants"); const errorHandler_1 = __importDefault(require("../../helper/errorHandler")); const dateTimeFormatParser_1 = require("../../helper/dateTimeFormatParser"); /** * @class formatter * @memberof util */ class Formatter { ErrorHandler = new errorHandler_1.default(); // =================================== STRING =================================== /** * @function sliceStringAt * @memberOf util.formatter * @description Slices the given string beginning at a specific substring. * @param {String} input - The input string to slice. * @param {String} slicePoint - The substring at which the input string is being sliced. * @param {number} length - The required length of the returning string (starting at the index of the passed slice point). * @returns {String} The sliced string. * @example const sliced = util.formatter.sliceStringAt("prefixNR12345postfix", "NR", 7); * // returns "NR12345" */ sliceStringAt(input, slicePoint, length) { if (input && slicePoint && length) { const index = input.indexOf(slicePoint); if (index !== -1) { return input.slice(index, index + length); } else { return this.ErrorHandler.logException(new Error(`Char '${slicePoint}' not found in input '${input}'.`)); } } else { return this.ErrorHandler.logException(new Error("Incorrect or missing arguments.")); } } /** * @function sliceStringAfter * @memberOf util.formatter * @description Slices the given string after a specific substring. * @param {String} input - The input string to slice. * @param {String} slicePoint - The substring after which the input string is being sliced. * @param {number} length - The required length of the returning string (starting at the index after the passed slice point). * @returns {String} The sliced string. * @example const sliced = util.formatter.sliceStringAfter("prefixNR12345postfix", "NR", 5); * // returns "12345" */ sliceStringAfter(input, slicePoint, length) { if (input && slicePoint && length) { let index = input.indexOf(slicePoint); if (index !== -1) { index = index + slicePoint.length; return input.slice(index, index + length); } return this.ErrorHandler.logException(new Error(`Char '${slicePoint}' not found in input '${input}'.`)); } return this.ErrorHandler.logException(new Error("Incorrect or missing arguments.")); } /** * @function trimString * @memberOf util.formatter * @description Removes whitespace from both sides of the given string. * @param {String} input - The input string to trim. * @example const trimmed = util.formatter.trimString(" value "); * // returns "value" */ trimString(input) { if (input) { return input.trim(); } return this.ErrorHandler.logException(new Error("Incorrect or missing arguments.")); } /** * @function extractNumberFromString * @memberOf util.formatter * @description Extracts all numbers from a string. * @param {String} input - The input string to extract the number. * @param {number} [index=0] - If there are multiple numbers in the string you can pass an index to return a specific number. * @returns {String} The extracted number. * @example const extracted = util.formatter.extractNumberFromString("prefixNR12345postfix"); * // returns "12345" * @example const extracted = util.formatter.extractNumberFromString("first12345 someText second 20 abc", 1); * // returns "20" */ extractNumberFromString(input, index = 0) { if (input) { // @ts-ignore return input.match(/\d+/g).map(Number)[index].toString(); } return this.ErrorHandler.logException(new Error("Incorrect or missing arguments.")); } /** * @function stringifyJSON * @memberOf util.formatter * @description Converts a JSON object to string. * @param {Object} object - The JSON to be converted. * @returns {String} The converted JSON object. * @example console.log(`Printing the current selector: ${util.formatter.stringifyJSON(selector)}`); */ stringifyJSON(object) { try { return JSON.stringify(object); } catch (error) { return this.ErrorHandler.logException(error, "Incorrect JSON object."); } } // =================================== NUMBER =================================== /** * @function addRemoveLeadingZeros * @memberOf util.formatter * @description Adds or removes leading zeros to the passed number to format it to the required length. * @param {String} number - The number to be formatted. * @param {Number} length - The required length of the number. * @returns {String} The formatted number. * @example const itemNumber = util.formatter.addRemoveLeadingZeros(10, 5); */ addRemoveLeadingZeros(number, length) { const numberParsed = parseInt(number, 10); const zero = "0"; const char = zero.repeat(length) + numberParsed; return char.slice(-length); } // =================================== DATE =================================== /** * @function formatDate * @memberOf util.formatter * @description formats date. * @param {Date} date - The date object to be formatted. * @param {String} format - The expected format ("mm/dd/yyyy", "mm-dd-yyyy", "dd.mm.yyyy", "dd/mm/yyyy", "yyyymmdd", "yyyy/mm/dd", * "yyyy.mm.dd", "yyyy-mm-dd", "dd.mm.yyyy.hh.mm", "mmm dd, yyyy", "mmm d, yyyy", "g.yy.mm.dd", "g/yy/mm/dd", "g-yy-mm-dd" "datetime", "object"). * @param {String} [locale="en-US"] - The locale format of the date. E.g. "en-US", "de-DE", etc. * @returns {String} The formatted date as string. * @example const date = new Date(2020, 0, 17); * const formattedDate = util.formatter.formatDate(date, "mm/dd/yyyy"); * // returns "01/17/2020" * @example const date = new Date(2022, 3, 12); * const formattedDate = util.formatter.formatDate(date, "mmm dd, yyyy"); * // returns "Apr 03, 2022" */ formatDate(date, format = process.env.USER_SETTINGS_DATE_FORMAT ? process.env.USER_SETTINGS_DATE_FORMAT : formatter_constants_1.DateFormats.OBJECT, locale = "en-US") { if (format) { format = format.toLowerCase(); } let formattedDate = date; let hour = date.getHours(); let min = date.getMinutes(); let sec = date.getSeconds(); let dd = date.getDate(); let mm = date.getMonth() + 1; const month = date.toLocaleString(locale, { month: "short" }); const yyyy = date.getFullYear(); if (sec < 10) { sec = `0${sec}`; } if (min < 10) { min = `0${min}`; } if (hour < 10) { hour = `0${hour}`; } if (dd < 10 && format !== formatter_constants_1.DateFormats.MONTH_DAY_YEAR_COMMA_SHORT) { dd = `0${dd}`; } if (mm < 10) { mm = `0${mm}`; } if (format) { switch (format) { case formatter_constants_1.DateFormats.MONTH_DAY_YEAR_SLASH: formattedDate = `${mm}/${dd}/${yyyy}`; break; case formatter_constants_1.DateFormats.MONTH_DAY_YEAR_DASH: formattedDate = `${mm}-${dd}-${yyyy}`; break; case formatter_constants_1.DateFormats.DAY_MONTH_YEAR_DOT: formattedDate = `${dd}.${mm}.${yyyy}`; break; case formatter_constants_1.DateFormats.DAY_MONTH_YEAR_SLASH: formattedDate = `${dd}/${mm}/${yyyy}`; break; case formatter_constants_1.DateFormats.YEAR_MONTH_DAY_PLAIN: formattedDate = `${yyyy}${mm}${dd}`; break; case formatter_constants_1.DateFormats.YEAR_MONTH_DAY_SLASH: formattedDate = `${yyyy}/${mm}/${dd}`; break; case formatter_constants_1.DateFormats.YEAR_MONTH_DAY_DOT: formattedDate = `${yyyy}.${mm}.${dd}`; break; case formatter_constants_1.DateFormats.YEAR_MONTH_DAY_DASH: formattedDate = `${yyyy}-${mm}-${dd}`; break; case formatter_constants_1.DateFormats.DAY_MONTH_YEAR_TIME_DOT: formattedDate = `${dd}.${mm}.${yyyy}.${hour}.${min}`; break; case formatter_constants_1.DateFormats.MONTH_DAY_YEAR_COMMA: formattedDate = `${month} ${dd}, ${yyyy}`; break; case formatter_constants_1.DateFormats.MONTH_DAY_YEAR_COMMA_SHORT: formattedDate = `${month} ${dd}, ${yyyy}`; break; case formatter_constants_1.DateFormats.DATETIME: formattedDate = `datetime'${yyyy}-${mm}-${dd}T${hour}:${min}:${sec}'`; break; case formatter_constants_1.DateFormats.OBJECT: formattedDate = date; break; case formatter_constants_1.DateFormats.JAPANESE_DOT: formattedDate = `${date.toLocaleDateString(locale, { era: "short" })}.${mm}.${dd}`; break; case formatter_constants_1.DateFormats.JAPANESE_SLASH: formattedDate = `${date.toLocaleDateString(locale, { era: "short" })}/${mm}/${dd}`; break; case formatter_constants_1.DateFormats.JAPANESE_DASH: formattedDate = `${date.toLocaleDateString(locale, { era: "short" })}-${mm}-${dd}`; break; default: break; } } return formattedDate; } /** * @function formatDateWithTime * @memberOf util.formatter * @description formats date with time. * @param {Date} date - The date object to be formatted. * @param {String} format - The expected format ("datetime", "object", "mm/dd/yyyy HH\:mm:ss", "dd.mm.yyyy h\:mm:ss a", "dd/mm/yyyy HH\:mm:ss z", "yyyymmdd h\:mm:ss a z", "yyyy/mm/dd HH\:mm", "mmm dd, yyyy h\:mm a", "mmm d, yyyy HH", "mmm d, yyyy h a", etc.).<br> * See the `format` argument of the {@link common.date.calculateWithTime} function for more details on the available formats. * @param {String} [locale="en-US"] - The locale format of the date. E.g. "en-US", "de-DE", etc. * @returns {String|Date} The formatted date with time as string or date object. * @example const date = new Date(2020, 0, 17, 15, 30, 45); * const formattedDate = util.formatter.formatDateWithTime(date, "mm/dd/yyyy HH:mm:ss"); * // returns "01/17/2020 15:30:45" * @example const date = new Date(2022, 3, 12, 9, 5, 0); * const formattedDate = util.formatter.formatDateWithTime(date, "mmm dd, yyyy h:mm:ss a"); * // returns "Apr 12, 2022 9:05:00 AM" * @example const date = new Date(2022, 3, 12, 9, 5, 0); * const formattedDate = util.formatter.formatDateWithTime(date, "dd/mm/yyyy HH:mm:ss z"); * // returns "12/04/2022 09:05:00 GMT+02:00" * @example const date = new Date(2022, 3, 12, 9, 5, 0); * const formattedDate = util.formatter.formatDateWithTime(date, "yyyy/mm/dd HH:mm"); * // returns "2022/04/12 09:05" * @example const date = new Date(2022, 3, 12, 9, 5, 0); * const formattedDate = util.formatter.formatDateWithTime(date, "mmm dd, yyyy h:mm a"); * // returns "Apr 12, 2022 9:05 AM" */ formatDateWithTime(date, format = formatter_constants_1.DateFormats.OBJECT, locale = "en-US") { const dateFormat = dateTimeFormatParser_1.DateTimeFormatParser.extractDateFormat(format); this._validateDateFormat(format, dateFormat); const dateFormatted = this.formatDate(date, dateFormat, locale); if (this._containsTimeInDateFormat(dateFormat)) { return dateFormatted; } const timeFormatted = this._formatTime(date, format); const delimiter = dateTimeFormatParser_1.DateTimeFormatParser.extractDelimiter(format); return `${dateFormatted}${delimiter}${timeFormatted}`; } // =================================== HELPER =================================== _validateDateFormat(format, dateFormat) { if (this._containsTimeInDateFormat(dateFormat) && !(format.toString() === dateFormat.toString())) { throw new Error(`Invalid date time format: if you want to use '${dateFormat}' format, please use only '${dateFormat}' without any additional text`); } } _containsTimeInDateFormat(dateFormat) { return dateFormat === formatter_constants_1.DateFormats.DATETIME || dateFormat === formatter_constants_1.DateFormats.DAY_MONTH_YEAR_TIME_DOT || dateFormat === formatter_constants_1.DateFormats.OBJECT; } _formatTime(date, format) { const timeFormat = dateTimeFormatParser_1.DateTimeFormatParser.extractTimeFormat(format); return timeFormat.replace(/HH|h|mm|ss|a|z/g, (token) => this._replaceTimeFormatToken(date, token)); } _replaceTimeFormatToken(date, token) { switch (token) { case "HH": return date.getHours().toString().padStart(2, "0"); case "h": return ((date.getHours() % 12) || 12).toString(); case "mm": return date.getMinutes().toString().padStart(2, "0"); case "ss": return date.getSeconds().toString().padStart(2, "0"); case "a": return date.getHours() < 12 ? "AM" : "PM"; case "z": return this._formatTimeOffset(date); default: return token; } } _formatTimeOffset(date) { const offset = date.getTimezoneOffset(); const sign = offset < 0 ? "+" : "-"; const hours = Math.abs(Math.floor(offset / 60)).toString().padStart(2, "0"); const minutes = Math.abs(offset % 60).toString().padStart(2, "0"); return `GMT${sign}${hours}:${minutes}`; } } exports.Formatter = Formatter; exports.default = new Formatter(); //# sourceMappingURL=formatter.js.map