A collection of useful TypeScript/JavaScript utilities for crypto, date, string, number, JSON operations and more.
—
Function introspection and utility operations including parameter name extraction and no-op functions for development and testing scenarios.
Empty function that accepts any arguments and returns undefined, useful for default callbacks and testing.
/**
* Empty function that does nothing
* @param _args - Any number of arguments (ignored)
* @returns undefined
*/
function noop(..._args: any[]): any;Usage Examples:
import { noop } from "utility";
// Default callback parameter
function processData(data: any[], callback: Function = noop) {
// Process data...
callback(result);
}
// Event handler placeholder
const eventHandlers = {
onSuccess: noop,
onError: noop,
onComplete: noop
};
// Optional callback in async operations
async function fetchData(url: string, onProgress: Function = noop) {
onProgress(0);
const response = await fetch(url);
onProgress(50);
const data = await response.json();
onProgress(100);
return data;
}
// Testing scenarios
function setupMockHandlers() {
return {
log: noop, // Disable logging in tests
warn: noop, // Disable warnings in tests
error: console.error // Keep errors for debugging
};
}
// Conditional operations
const debugLog = process.env.NODE_ENV === 'development' ? console.log : noop;
debugLog('Debug information'); // Only logs in development
// Interface implementation
interface EventEmitter {
onData: (data: any) => void;
onError: (error: Error) => void;
onEnd: () => void;
}
const silentEmitter: EventEmitter = {
onData: noop,
onError: noop,
onEnd: noop
};Extract parameter names from function signatures with optional caching for performance.
/**
* Get function parameter names
* @param func - Function to analyze
* @param cache - Enable caching (defaults to true)
* @returns Array of parameter names
*/
function getParamNames(func: (...args: any[]) => any, cache?: boolean): string[];Usage Examples:
import { getParamNames } from "utility";
// Basic parameter extraction
function userLogin(username: string, password: string, rememberMe: boolean) {
// Implementation...
}
const params = getParamNames(userLogin);
// Result: ['username', 'password', 'rememberMe']
// Arrow function parameter extraction
const calculate = (x: number, y: number, operation?: string) => x + y;
const calcParams = getParamNames(calculate);
// Result: ['x', 'y', 'operation']
// Function with default parameters
function createUser(name: string, age = 25, active = true) {
// Implementation...
}
const userParams = getParamNames(createUser);
// Result: ['name', 'age', 'active']
// Disable caching for dynamic analysis
function dynamicAnalysis(func: Function) {
return getParamNames(func, false); // Don't cache for one-time analysis
}
// API documentation generation
function generateApiDocs(apiFunction: Function) {
const params = getParamNames(apiFunction);
return {
name: apiFunction.name,
parameters: params.map(param => ({
name: param,
required: true, // Could be enhanced to detect optional params
type: 'any' // Could be enhanced with TypeScript reflection
}))
};
}
// Form validation based on function signature
function createValidationRules(validatorFunc: Function) {
const paramNames = getParamNames(validatorFunc);
const rules: Record<string, any> = {};
paramNames.forEach(param => {
rules[param] = { required: true };
});
return rules;
}
// Testing utilities
function mockFunction(originalFunc: Function) {
const params = getParamNames(originalFunc);
console.log(`Mocking function with parameters: ${params.join(', ')}`);
return function(...args: any[]) {
console.log(`Mock called with:`, params.map((name, i) => `${name}=${args[i]}`));
return null;
};
}
// Cached vs uncached performance
function performanceTest() {
function testFunc(a: any, b: any, c: any) {}
// First call caches the result
console.time('cached');
getParamNames(testFunc); // Caches result
getParamNames(testFunc); // Uses cache
console.timeEnd('cached');
// Uncached calls
console.time('uncached');
getParamNames(testFunc, false); // No cache
getParamNames(testFunc, false); // No cache
console.timeEnd('uncached');
}Install with Tessl CLI
npx tessl i tessl/npm-utility