UNPKG

coach-core

Version:
129 lines (113 loc) 2.96 kB
import urlParser from 'node:url'; export function isHTTP2(page) { return page.httpType === 'h2'; } export function isHTTP3(page) { return page.httpType.startsWith('h3'); } /** * Get the hostname from a URL string. * @param {string} url The URL like https://www.example.com/hepp * @returns {string} the hostname */ export function getHostname(url) { if (!url) { return ''; } return urlParser.parse(url).hostname || ''; } /** * Convert bytes to human readable. * @param {Number} bytes * @returns {String} human readable file size */ export function formatBytes(bytes) { var sizes = ['B', 'kB', 'MB', 'GB', 'TB']; if (bytes === 0) { return '0 B'; } var i = Number.parseInt(Math.floor(Math.log(bytes) / Math.log(1000)), 10); return Math.round((bytes / Math.pow(1000, i)) * 10) / 10 + ' ' + sizes[i]; } /** * Print seconds as the largest available time. * @param {int} seconds A number in seconds * @return {String} The time in nearest largest definition. */ export function prettyPrintSeconds(seconds) { if (seconds === undefined) { return ''; } var secondsPerYear = 365 * 24 * 60 * 60, secondsPerWeek = 60 * 60 * 24 * 7, secondsPerDay = 60 * 60 * 24, secondsPerHour = 60 * 60, secondsPerMinute = 60, sign = seconds < 0 ? '-' : ''; if (seconds < 0) { seconds = Math.abs(seconds); } if (seconds / secondsPerYear >= 1) { return ( sign + Math.round(seconds / secondsPerYear) + ' year' + (Math.round(seconds / secondsPerYear) > 1 ? 's' : '') ); } else if (seconds / secondsPerWeek >= 1) { return ( sign + Math.round(seconds / secondsPerWeek) + ' week' + (Math.round(seconds / secondsPerWeek) > 1 ? 's' : '') ); } else if (seconds / secondsPerDay >= 1) { return ( sign + Math.round(seconds / secondsPerDay) + ' day' + (Math.round(seconds / secondsPerDay) > 1 ? 's' : '') ); } else if (seconds / secondsPerHour >= 1) { return ( sign + Math.round(seconds / secondsPerHour) + ' hour' + (Math.round(seconds / secondsPerHour) > 1 ? 's' : '') ); } else if (seconds / secondsPerMinute >= 1) { return ( sign + Math.round(seconds / secondsPerMinute) + ' minute' + (Math.round(seconds / secondsPerMinute) > 1 ? 's' : '') ); } else { return ( sign + seconds + ' second' + (seconds > 1 || seconds === 0 ? 's' : '') ); } } export function human(node, pretty) { if (!node) { return; } let clean = {}; for (const key of Object.keys(node)) { clean[key] = pretty(node[key]); } return clean; } export function shortURL(url) { if (url.length > 40) { let shortUrl = url.replace(/\?.*/, ''); url = shortUrl.slice(0, 20) + '...' + shortUrl.slice(-17); } return url; } export function plural(number, text) { if (number > 1) { text += 's'; } return `${number} ${text}`; }