@projectlibertylabs/p2p-peer-test
Version:
CLI tool to test libp2p connections and discover peer protocols
92 lines (82 loc) • 3.14 kB
JavaScript
/**
* Pure utility functions for the libp2p peer tester
*/
/**
* Creates a promise that races against a timeout
* @param {Promise} promise - The promise to race
* @param {number} timeoutMs - Timeout in milliseconds
* @param {string} timeoutError - Error message for timeout
* @returns {Promise} Promise that resolves with the original result or rejects with timeout error
*/
export const createPromiseWithTimeout = (promise, timeoutMs, timeoutError) => {
const timeoutPromise = new Promise((_, reject) =>
setTimeout(() => reject(new Error(timeoutError)), timeoutMs)
);
return Promise.race([promise, timeoutPromise]);
};
/**
* Safely parses an integer with validation
* @param {string|number} value - Value to parse
* @param {number} defaultValue - Default value if parsing fails
* @param {Function} validator - Optional validation function
* @returns {number|null} Parsed integer or null if invalid
*/
export const safeParseInt = (value, defaultValue, validator = () => true) => {
const parsed = parseInt(value || defaultValue);
if (isNaN(parsed) || !validator(parsed)) {
return null;
}
return parsed;
};
/**
* Measures duration from a start time
* @param {number} startTime - Start time from performance.now()
* @returns {number} Duration in milliseconds rounded to nearest integer
*/
export const measureDuration = (startTime) => Math.round(performance.now() - startTime);
/**
* Creates a pipe function that applies functions left to right
* @param {...Function} fns - Functions to pipe
* @returns {Function} Function that pipes value through all functions
*/
export const pipe =
(...fns) =>
(value) =>
fns.reduce((acc, fn) => fn(acc), value);
/**
* Creates a compose function that applies functions right to left
* @param {...Function} fns - Functions to compose
* @returns {Function} Function that composes value through all functions
*/
export const compose =
(...fns) =>
(value) =>
fns.reduceRight((acc, fn) => fn(acc), value);
/**
* Checks if a value is null or undefined
* @param {*} value - Value to check
* @returns {boolean} True if value is null or undefined
*/
export const isNullOrUndefined = (value) => value === null || value === undefined;
/**
* Checks if a value is empty (null, undefined, empty string, or empty array)
* @param {*} value - Value to check
* @returns {boolean} True if value is considered empty
*/
export const isEmpty = (value) =>
isNullOrUndefined(value) ||
(typeof value === 'string' && value.trim() === '') ||
(Array.isArray(value) && value.length === 0);
/**
* Parses multiple multiaddrs from text input (separated by newlines or whitespace)
* @param {string} input - Text containing one or more multiaddrs
* @returns {string[]} Array of cleaned multiaddr strings
*/
export const parseMultiaddrs = (input) => {
if (isEmpty(input)) return [];
return input
.split(/[\r\n\s]+/) // Split on newlines or whitespace
.map((addr) => addr.trim())
.filter((addr) => addr.length > 0 && addr.startsWith('/')) // Only keep valid-looking multiaddrs
.filter((addr, index, arr) => arr.indexOf(addr) === index); // Remove duplicates
};