0
# Utility Modules
1
2
Internal utility modules providing helper functions for array operations, object manipulation, and class inheritance used throughout PEG.js.
3
4
## Capabilities
5
6
### Array Utilities
7
8
Collection of array manipulation functions for common operations like searching, mapping, and iteration.
9
10
```javascript { .api }
11
/**
12
* Array utility functions
13
*/
14
const arrays = {
15
/**
16
* Generate an array of integers in a range
17
* @param start - Starting number (inclusive)
18
* @param stop - Ending number (exclusive)
19
* @returns Array of integers from start to stop-1
20
*/
21
range: function(start, stop),
22
23
/**
24
* Find first element matching value or predicate
25
* @param array - Array to search
26
* @param valueOrPredicate - Value to match or predicate function
27
* @returns First matching element or undefined
28
*/
29
find: function(array, valueOrPredicate),
30
31
/**
32
* Find index of first element matching value or predicate
33
* @param array - Array to search
34
* @param valueOrPredicate - Value to match or predicate function
35
* @returns Index of first match or -1 if not found
36
*/
37
indexOf: function(array, valueOrPredicate),
38
39
/**
40
* Check if array contains value or element matching predicate
41
* @param array - Array to search
42
* @param valueOrPredicate - Value to match or predicate function
43
* @returns True if array contains matching element
44
*/
45
contains: function(array, valueOrPredicate),
46
47
/**
48
* Iterate over array elements
49
* @param array - Array to iterate
50
* @param iterator - Function called for each element (element, index)
51
*/
52
each: function(array, iterator),
53
54
/**
55
* Transform array elements using iterator function
56
* @param array - Array to transform
57
* @param iterator - Transform function (element, index) => newElement
58
* @returns New array with transformed elements
59
*/
60
map: function(array, iterator),
61
62
/**
63
* Extract property values from array of objects
64
* @param array - Array of objects
65
* @param key - Property key to extract
66
* @returns Array of property values
67
*/
68
pluck: function(array, key),
69
70
/**
71
* Test if all elements pass predicate test
72
* @param array - Array to test
73
* @param predicate - Test function (element) => boolean
74
* @returns True if all elements pass test
75
*/
76
every: function(array, predicate),
77
78
/**
79
* Test if any element passes predicate test
80
* @param array - Array to test
81
* @param predicate - Test function (element) => boolean
82
* @returns True if any element passes test
83
*/
84
some: function(array, predicate)
85
};
86
```
87
88
**Usage Examples:**
89
90
```javascript
91
const peg = require("pegjs");
92
// Note: Utility modules are internal and not directly exported
93
// These examples show conceptual usage
94
95
// Generate range of numbers
96
const numbers = arrays.range(1, 6); // [1, 2, 3, 4, 5]
97
98
// Find elements
99
const users = [
100
{ name: "Alice", age: 25 },
101
{ name: "Bob", age: 30 }
102
];
103
const alice = arrays.find(users, user => user.name === "Alice");
104
const ageIndex = arrays.indexOf(users, user => user.age === 30); // 1
105
106
// Transform arrays
107
const names = arrays.pluck(users, "name"); // ["Alice", "Bob"]
108
const adults = arrays.every(users, user => user.age >= 18); // true
109
110
// Iterate
111
arrays.each(users, (user, index) => {
112
console.log(`User ${index}: ${user.name}`);
113
});
114
```
115
116
### Object Utilities
117
118
Functions for object manipulation including key/value extraction, cloning, and setting defaults.
119
120
```javascript { .api }
121
/**
122
* Object utility functions
123
*/
124
const objects = {
125
/**
126
* Get array of object's own property keys
127
* @param object - Object to get keys from
128
* @returns Array of property keys
129
*/
130
keys: function(object),
131
132
/**
133
* Get array of object's own property values
134
* @param object - Object to get values from
135
* @returns Array of property values
136
*/
137
values: function(object),
138
139
/**
140
* Create shallow clone of object
141
* @param object - Object to clone
142
* @returns New object with same properties
143
*/
144
clone: function(object),
145
146
/**
147
* Set default values on object (modifies original object)
148
* @param object - Object to set defaults on
149
* @param defaults - Object with default values
150
*/
151
defaults: function(object, defaults)
152
};
153
```
154
155
**Usage Examples:**
156
157
```javascript
158
// Note: Utility modules are internal and not directly exported
159
// These examples show conceptual usage
160
161
const config = {
162
format: "commonjs",
163
optimize: "speed"
164
};
165
166
// Get keys and values
167
const keys = objects.keys(config); // ["format", "optimize"]
168
const values = objects.values(config); // ["commonjs", "speed"]
169
170
// Clone object
171
const configCopy = objects.clone(config);
172
173
// Set defaults
174
const options = { format: "amd" };
175
objects.defaults(options, {
176
format: "bare", // Won't override existing value
177
optimize: "speed", // Will be added
178
cache: false // Will be added
179
});
180
// options is now: { format: "amd", optimize: "speed", cache: false }
181
```
182
183
### Class Utilities
184
185
Utility for implementing classical inheritance patterns in JavaScript.
186
187
```javascript { .api }
188
/**
189
* Class inheritance utilities
190
*/
191
const classes = {
192
/**
193
* Set up prototype-based inheritance between classes
194
* @param child - Constructor function for child class
195
* @param parent - Constructor function for parent class
196
*/
197
subclass: function(child, parent)
198
};
199
```
200
201
**Usage Examples:**
202
203
```javascript
204
// Note: Utility modules are internal and not directly exported
205
// This example shows how it's used within PEG.js
206
207
// Create parent class
208
function BaseError(message) {
209
this.message = message;
210
this.name = "BaseError";
211
}
212
213
// Create child class
214
function GrammarError(message, location) {
215
BaseError.call(this, message);
216
this.name = "GrammarError";
217
this.location = location;
218
}
219
220
// Set up inheritance
221
classes.subclass(GrammarError, BaseError);
222
223
// Now GrammarError inherits from BaseError
224
const error = new GrammarError("Invalid rule", { line: 1, column: 5 });
225
console.log(error instanceof BaseError); // true
226
console.log(error instanceof GrammarError); // true
227
```
228
229
## Internal Usage
230
231
These utility modules are used internally throughout PEG.js:
232
233
- **Arrays**: Used in compiler passes for AST traversal and manipulation
234
- **Objects**: Used for options processing and configuration management
235
- **Classes**: Used for error class inheritance (GrammarError extends Error)
236
237
While these modules are not part of the public API, understanding their functionality helps when:
238
239
- Writing custom compiler passes or plugins
240
- Understanding PEG.js source code
241
- Contributing to PEG.js development
242
243
## Browser Compatibility
244
245
These utilities are designed to work in older JavaScript environments and provide cross-browser compatibility:
246
247
- No dependency on modern JavaScript features
248
- Compatible with ES3/ES5 environments
249
- Polyfills for missing native methods like `Array.prototype.indexOf`