0
# Utilities
1
2
Common utility functions for object manipulation, type checking, string processing, and general-purpose operations. All utilities are available through `Mock.Util`.
3
4
## Capabilities
5
6
### Object Manipulation
7
8
Core functions for working with objects and extending their properties.
9
10
```javascript { .api }
11
/**
12
* Extend target object with properties from source objects
13
* @param target - Target object to extend
14
* @param sources - Source objects to merge from
15
* @returns Extended target object
16
*/
17
Mock.Util.extend(target: any, ...sources: any[]): any;
18
19
/**
20
* Get all enumerable property keys from object
21
* @param obj - Object to get keys from
22
* @returns Array of property keys
23
*/
24
Mock.Util.keys(obj: any): string[];
25
26
/**
27
* Get all enumerable property values from object
28
* @param obj - Object to get values from
29
* @returns Array of property values
30
*/
31
Mock.Util.values(obj: any): any[];
32
```
33
34
**Object Examples:**
35
36
```javascript
37
// Extend objects
38
const target = { a: 1, b: 2 };
39
const source1 = { b: 3, c: 4 };
40
const source2 = { c: 5, d: 6 };
41
42
const result = Mock.Util.extend(target, source1, source2);
43
// Result: { a: 1, b: 3, c: 5, d: 6 }
44
45
// Get object keys and values
46
const obj = { name: 'John', age: 30, city: 'NYC' };
47
const keys = Mock.Util.keys(obj); // ['name', 'age', 'city']
48
const values = Mock.Util.values(obj); // ['John', 30, 'NYC']
49
50
// Deep extend with nested objects
51
const deep1 = {
52
user: { id: 1, name: 'John' },
53
settings: { theme: 'light' }
54
};
55
const deep2 = {
56
user: { email: 'john@example.com' },
57
settings: { language: 'en' }
58
};
59
60
Mock.Util.extend(deep1, deep2);
61
// Result: {
62
// user: { id: 1, name: 'John', email: 'john@example.com' },
63
// settings: { theme: 'light', language: 'en' }
64
// }
65
```
66
67
### Iteration
68
69
Functions for iterating over objects, arrays, and other iterable structures.
70
71
```javascript { .api }
72
/**
73
* Iterate over object properties or array elements
74
* @param obj - Object, array, or number to iterate over
75
* @param iterator - Iterator function called for each item
76
* @param context - Optional context for iterator function
77
*/
78
Mock.Util.each(obj: any, iterator: (value: any, key: any, obj: any) => any, context?: any): void;
79
```
80
81
**Iteration Examples:**
82
83
```javascript
84
// Iterate over array
85
Mock.Util.each([1, 2, 3], function(value, index) {
86
console.log(`${index}: ${value}`);
87
});
88
// Output: 0: 1, 1: 2, 2: 3
89
90
// Iterate over object
91
Mock.Util.each({ a: 1, b: 2, c: 3 }, function(value, key) {
92
console.log(`${key}: ${value}`);
93
});
94
// Output: a: 1, b: 2, c: 3
95
96
// Iterate N times (when obj is number)
97
Mock.Util.each(5, function(value, index) {
98
console.log(`Iteration ${index}`);
99
});
100
// Output: Iteration 0, Iteration 1, etc.
101
102
// Early termination (return false to break)
103
Mock.Util.each([1, 2, 3, 4, 5], function(value) {
104
if (value === 3) return false; // Break iteration
105
console.log(value);
106
});
107
// Output: 1, 2 (stops at 3)
108
109
// With context
110
const counter = { count: 0 };
111
Mock.Util.each([1, 2, 3], function(value) {
112
this.count += value;
113
}, counter);
114
console.log(counter.count); // 6
115
```
116
117
### Type Checking
118
119
Functions for determining and validating data types.
120
121
```javascript { .api }
122
/**
123
* Get the type of a value as a lowercase string
124
* @param obj - Value to check type of
125
* @returns Type string ('string', 'number', 'boolean', 'object', 'array', 'function', 'regexp', 'null', 'undefined')
126
*/
127
Mock.Util.type(obj: any): string;
128
129
/**
130
* Check if value is a string
131
* @param obj - Value to check
132
* @returns True if string
133
*/
134
Mock.Util.isString(obj: any): boolean;
135
136
/**
137
* Check if value is an object (but not array or null)
138
* @param obj - Value to check
139
* @returns True if object
140
*/
141
Mock.Util.isObject(obj: any): boolean;
142
143
/**
144
* Check if value is an array
145
* @param obj - Value to check
146
* @returns True if array
147
*/
148
Mock.Util.isArray(obj: any): boolean;
149
150
/**
151
* Check if value is a regular expression
152
* @param obj - Value to check
153
* @returns True if RegExp
154
*/
155
Mock.Util.isRegExp(obj: any): boolean;
156
157
/**
158
* Check if value is a function
159
* @param obj - Value to check
160
* @returns True if function
161
*/
162
Mock.Util.isFunction(obj: any): boolean;
163
164
/**
165
* Check if value is an object or array
166
* @param obj - Value to check
167
* @returns True if object or array
168
*/
169
Mock.Util.isObjectOrArray(obj: any): boolean;
170
171
/**
172
* Check if value is numeric (can be parsed as number)
173
* @param value - Value to check
174
* @returns True if numeric
175
*/
176
Mock.Util.isNumeric(value: any): boolean;
177
```
178
179
**Type Checking Examples:**
180
181
```javascript
182
// Basic type checking
183
Mock.Util.type('hello'); // 'string'
184
Mock.Util.type(123); // 'number'
185
Mock.Util.type(true); // 'boolean'
186
Mock.Util.type([1, 2, 3]); // 'array'
187
Mock.Util.type({a: 1}); // 'object'
188
Mock.Util.type(null); // 'null'
189
Mock.Util.type(undefined); // 'undefined'
190
Mock.Util.type(/regex/); // 'regexp'
191
Mock.Util.type(function(){}); // 'function'
192
193
// Specific type checks
194
Mock.Util.isString('hello'); // true
195
Mock.Util.isString(123); // false
196
197
Mock.Util.isArray([1, 2, 3]); // true
198
Mock.Util.isArray({}); // false
199
200
Mock.Util.isObject({a: 1}); // true
201
Mock.Util.isObject([1, 2]); // false
202
Mock.Util.isObject(null); // false
203
204
Mock.Util.isNumeric('123'); // true
205
Mock.Util.isNumeric('12.5'); // true
206
Mock.Util.isNumeric('abc'); // false
207
Mock.Util.isNumeric(NaN); // false
208
209
// Combined checks
210
Mock.Util.isObjectOrArray({}); // true
211
Mock.Util.isObjectOrArray([]); // true
212
Mock.Util.isObjectOrArray('str'); // false
213
```
214
215
### String Processing
216
217
Utilities for working with multi-line strings and text processing.
218
219
```javascript { .api }
220
/**
221
* Extract multi-line string from function comment block
222
* @param fn - Function containing /* comment */ block
223
* @returns Cleaned multi-line string content
224
*/
225
Mock.Util.heredoc(fn: Function): string;
226
227
/**
228
* No-operation function (does nothing)
229
* @returns undefined
230
*/
231
Mock.Util.noop(): void;
232
```
233
234
**String Processing Examples:**
235
236
```javascript
237
// Heredoc for multi-line strings
238
const template = Mock.Util.heredoc(function() {
239
/*!
240
<div class="user-card">
241
<h3>{{name}}</h3>
242
<p>Email: {{email}}</p>
243
<p>Age: {{age}}</p>
244
</div>
245
*/
246
});
247
248
console.log(template);
249
// Output:
250
// <div class="user-card">
251
// <h3>{{name}}</h3>
252
// <p>Email: {{email}}</p>
253
// <p>Age: {{age}}</p>
254
// </div>
255
256
// Use with Mock.js templates
257
const htmlTemplate = Mock.Util.heredoc(function() {
258
/*!
259
<article>
260
<h1>{{title}}</h1>
261
<p>By {{author}} on {{date}}</p>
262
<div>{{content}}</div>
263
</article>
264
*/
265
});
266
267
// Generate data to populate template
268
const articleData = Mock.mock({
269
title: '@title(3, 8)',
270
author: '@name',
271
date: '@date(yyyy-MM-dd)',
272
content: '@paragraph(3, 6)'
273
});
274
275
// Replace placeholders with actual data
276
let populatedHtml = htmlTemplate;
277
Object.keys(articleData).forEach(key => {
278
populatedHtml = populatedHtml.replace(
279
new RegExp(`{{${key}}}`, 'g'),
280
articleData[key]
281
);
282
});
283
```
284
285
### Practical Usage Patterns
286
287
Common patterns for using Mock.js utilities in real applications.
288
289
**Data Processing Pipeline:**
290
291
```javascript
292
function processUserData(rawUsers) {
293
const processedUsers = [];
294
295
Mock.Util.each(rawUsers, function(user, index) {
296
// Type validation
297
if (!Mock.Util.isObject(user)) {
298
console.warn(`User at index ${index} is not an object`);
299
return; // Skip invalid user
300
}
301
302
// Process user data
303
const processed = Mock.Util.extend({}, user, {
304
id: user.id || Mock.Random.increment(),
305
name: Mock.Util.isString(user.name) ? user.name : '@name',
306
email: Mock.Util.isString(user.email) ? user.email : '@email',
307
createdAt: user.createdAt || Mock.Random.now()
308
});
309
310
processedUsers.push(processed);
311
});
312
313
return processedUsers;
314
}
315
316
// Usage
317
const rawData = [
318
{ name: 'John', email: 'john@example.com' },
319
{ name: 'Jane' }, // Missing email
320
'invalid', // Not an object
321
{ name: 'Bob', email: 'bob@example.com', id: 100 }
322
];
323
324
const processed = processUserData(rawData);
325
console.log(processed);
326
```
327
328
**Configuration Merging:**
329
330
```javascript
331
function createMockConfig(userConfig) {
332
const defaultConfig = {
333
timeout: '200-600',
334
responseType: 'json',
335
headers: {
336
'Content-Type': 'application/json'
337
},
338
debug: false
339
};
340
341
const finalConfig = Mock.Util.extend({}, defaultConfig, userConfig);
342
343
// Validate configuration
344
if (!Mock.Util.isString(finalConfig.timeout) && !Mock.Util.isNumeric(finalConfig.timeout)) {
345
console.warn('Invalid timeout, using default');
346
finalConfig.timeout = defaultConfig.timeout;
347
}
348
349
return finalConfig;
350
}
351
352
// Usage
353
const config = createMockConfig({
354
timeout: 500,
355
debug: true,
356
headers: {
357
'Authorization': 'Bearer token123'
358
}
359
});
360
```
361
362
**Template Validation Helper:**
363
364
```javascript
365
function validateTemplate(template) {
366
const errors = [];
367
368
function checkNode(node, path = []) {
369
const nodeType = Mock.Util.type(node);
370
371
if (Mock.Util.isObject(node)) {
372
Mock.Util.each(node, function(value, key) {
373
checkNode(value, [...path, key]);
374
});
375
} else if (Mock.Util.isArray(node)) {
376
Mock.Util.each(node, function(value, index) {
377
checkNode(value, [...path, index]);
378
});
379
} else if (Mock.Util.isString(node) && node.startsWith('@')) {
380
// Validate placeholder
381
if (!node.match(/^@[a-zA-Z][a-zA-Z0-9]*(\([^)]*\))?$/)) {
382
errors.push({
383
path: path.join('.'),
384
message: `Invalid placeholder format: ${node}`
385
});
386
}
387
}
388
}
389
390
checkNode(template);
391
return errors;
392
}
393
394
// Usage
395
const template = {
396
users: [{
397
name: '@name',
398
email: '@invalid-placeholder', // Invalid
399
age: '@natural(18, 65)'
400
}]
401
};
402
403
const validationErrors = validateTemplate(template);
404
console.log(validationErrors);
405
```