0
# Function Utilities
1
2
Function introspection and utility operations including parameter name extraction and no-op functions for development and testing scenarios.
3
4
## Capabilities
5
6
### No-Operation Function
7
8
Empty function that accepts any arguments and returns undefined, useful for default callbacks and testing.
9
10
```typescript { .api }
11
/**
12
* Empty function that does nothing
13
* @param _args - Any number of arguments (ignored)
14
* @returns undefined
15
*/
16
function noop(..._args: any[]): any;
17
```
18
19
**Usage Examples:**
20
21
```typescript
22
import { noop } from "utility";
23
24
// Default callback parameter
25
function processData(data: any[], callback: Function = noop) {
26
// Process data...
27
callback(result);
28
}
29
30
// Event handler placeholder
31
const eventHandlers = {
32
onSuccess: noop,
33
onError: noop,
34
onComplete: noop
35
};
36
37
// Optional callback in async operations
38
async function fetchData(url: string, onProgress: Function = noop) {
39
onProgress(0);
40
const response = await fetch(url);
41
onProgress(50);
42
const data = await response.json();
43
onProgress(100);
44
return data;
45
}
46
47
// Testing scenarios
48
function setupMockHandlers() {
49
return {
50
log: noop, // Disable logging in tests
51
warn: noop, // Disable warnings in tests
52
error: console.error // Keep errors for debugging
53
};
54
}
55
56
// Conditional operations
57
const debugLog = process.env.NODE_ENV === 'development' ? console.log : noop;
58
debugLog('Debug information'); // Only logs in development
59
60
// Interface implementation
61
interface EventEmitter {
62
onData: (data: any) => void;
63
onError: (error: Error) => void;
64
onEnd: () => void;
65
}
66
67
const silentEmitter: EventEmitter = {
68
onData: noop,
69
onError: noop,
70
onEnd: noop
71
};
72
```
73
74
### Function Parameter Names
75
76
Extract parameter names from function signatures with optional caching for performance.
77
78
```typescript { .api }
79
/**
80
* Get function parameter names
81
* @param func - Function to analyze
82
* @param cache - Enable caching (defaults to true)
83
* @returns Array of parameter names
84
*/
85
function getParamNames(func: (...args: any[]) => any, cache?: boolean): string[];
86
```
87
88
**Usage Examples:**
89
90
```typescript
91
import { getParamNames } from "utility";
92
93
// Basic parameter extraction
94
function userLogin(username: string, password: string, rememberMe: boolean) {
95
// Implementation...
96
}
97
98
const params = getParamNames(userLogin);
99
// Result: ['username', 'password', 'rememberMe']
100
101
// Arrow function parameter extraction
102
const calculate = (x: number, y: number, operation?: string) => x + y;
103
const calcParams = getParamNames(calculate);
104
// Result: ['x', 'y', 'operation']
105
106
// Function with default parameters
107
function createUser(name: string, age = 25, active = true) {
108
// Implementation...
109
}
110
111
const userParams = getParamNames(createUser);
112
// Result: ['name', 'age', 'active']
113
114
// Disable caching for dynamic analysis
115
function dynamicAnalysis(func: Function) {
116
return getParamNames(func, false); // Don't cache for one-time analysis
117
}
118
119
// API documentation generation
120
function generateApiDocs(apiFunction: Function) {
121
const params = getParamNames(apiFunction);
122
return {
123
name: apiFunction.name,
124
parameters: params.map(param => ({
125
name: param,
126
required: true, // Could be enhanced to detect optional params
127
type: 'any' // Could be enhanced with TypeScript reflection
128
}))
129
};
130
}
131
132
// Form validation based on function signature
133
function createValidationRules(validatorFunc: Function) {
134
const paramNames = getParamNames(validatorFunc);
135
const rules: Record<string, any> = {};
136
137
paramNames.forEach(param => {
138
rules[param] = { required: true };
139
});
140
141
return rules;
142
}
143
144
// Testing utilities
145
function mockFunction(originalFunc: Function) {
146
const params = getParamNames(originalFunc);
147
console.log(`Mocking function with parameters: ${params.join(', ')}`);
148
149
return function(...args: any[]) {
150
console.log(`Mock called with:`, params.map((name, i) => `${name}=${args[i]}`));
151
return null;
152
};
153
}
154
155
// Cached vs uncached performance
156
function performanceTest() {
157
function testFunc(a: any, b: any, c: any) {}
158
159
// First call caches the result
160
console.time('cached');
161
getParamNames(testFunc); // Caches result
162
getParamNames(testFunc); // Uses cache
163
console.timeEnd('cached');
164
165
// Uncached calls
166
console.time('uncached');
167
getParamNames(testFunc, false); // No cache
168
getParamNames(testFunc, false); // No cache
169
console.timeEnd('uncached');
170
}
171
```