1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
|
# List Class
The `List` class is a fundamental data structure in CSSTree, used to represent the children of AST nodes. It provides a performant way to manipulate nodes during CSS parsing and transformation by avoiding the overhead of growing arrays and reducing common mistakes when modifying a list while iterating over it.
## Table of Contents
- [Introduction](#introduction)
- [List Structure](#list-structure)
- [List Items vs. Data](#list-items-vs-data)
- [Usage Examples](#usage-examples)
- [API Reference](#api-reference)
- [Static Methods](#static-methods)
- [Instance Methods](#instance-methods)
- [Properties](#properties)
- [Conversion Methods](#conversion-methods)
- [Traversal Methods](#traversal-methods)
- [Mutation Methods](#mutation-methods)
- [Array Compatibility](#array-compatibility)
- [Serialization](#serialization)
## Introduction
The `List` class implements a doubly linked list specifically optimized for AST node manipulation within CSSTree. By using a linked list instead of an array, it ensures efficient insertions and deletions without the need for memory reallocation or shifting elements, which can be costly with large AST.
This data structure is particularly useful when traversing and modifying the AST, as it helps avoid common pitfalls such as altering the collection while iterating over it.
## List Structure
The `List` is a doubly linked list where each element (item) contains references to its previous and next items, as well as the data (node) it holds.
```
List
┌──────┐
┌──────────────┼─head │
│ │ tail─┼──────────────┐
│ └──────┘ │
▼ ▼
Item Item Item Item
┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐
null ◀──┼─prev │◀───┼─prev │◀───┼─prev │◀───┼─prev │
│ next─┼───▶│ next─┼───▶│ next─┼───▶│ next─┼──▶ null
├──────┤ ├──────┤ ├──────┤ ├──────┤
│ data │ │ data │ │ data │ │ data │
└──────┘ └──────┘ └──────┘ └──────┘
```
## List Items vs. Data
In the `List` class, each node of the list is called an **item**, which contains:
- `prev`: Reference to the previous item.
- `next`: Reference to the next item.
- `data`: The actual data (AST node).
It's crucial to understand the distinction between the **item** and the **data** it holds. When manipulating the list, operations often involve items, especially when inserting or removing elements.
## Usage Examples
### Traversing and Modifying the List
When using CSSTree's `walk()` function to traverse the AST, you interact with `List` instances:
```js
csstree.walk(ast, function(node, item, list) {
// node: the current AST node (item.data)
// item: the current list item
// list: the list containing the item
// Remove the current node
list.remove(item);
// Insert a new node before the current item
const newItem = List.createItem(newNode);
list.insert(newItem, item);
// Alternatively, insert data directly
list.insertData(newNode, item);
// Insert a node after the current item
list.insert(List.createItem(anotherNode), item.next);
});
```
## API Reference
### Static Methods
#### `List.createItem(data)`
Creates a new list item containing the provided data.
- **Parameters:**
- `data`: The data to store in the item.
- **Returns:** A new list item.
```js
const item = List.createItem(node);
```
### Instance Methods
#### `constructor()`
Initializes a new empty `List`.
```js
const list = new List();
```
#### `createItem(data)`
Instance method to create a new list item.
- **Parameters:**
- `data`: The data to store in the item.
- **Returns:** A new list item.
```js
const item = list.createItem(node);
```
#### `[Symbol.iterator]()`
Allows the list to be iterable using `for...of` loops.
```js
for (const node of list) {
console.log(node);
}
```
### Properties
#### `size`
Returns the number of items in the list.
- **Type:** `number`
```js
console.log(list.size); // Outputs the size of the list
```
#### `isEmpty`
Checks if the list is empty.
- **Type:** `boolean`
```js
if (list.isEmpty) {
// The list is empty
}
```
#### `first`
Gets the data of the first item.
- **Type:** Same as the data stored in the list.
```js
const firstNode = list.first;
```
#### `last`
Gets the data of the last item.
- **Type:** Same as the data stored in the list.
```js
const lastNode = list.last;
```
## Conversion Methods
### `fromArray(array)`
Populates the list with items created from the given array.
- **Parameters:**
- `array`: An array of data elements.
- **Returns:** The `List` instance (for chaining).
```js
list.fromArray([node1, node2, node3]);
```
### `toArray()`
Converts the list to an array of data elements.
- **Returns:** An array of the data in the list.
```js
const nodes = list.toArray();
```
### `toJSON()`
Serializes the list to a JSON-compatible array.
- **Returns:** An array suitable for JSON serialization.
```js
const jsonString = JSON.stringify(list);
```
## Traversal Methods
### `forEach(fn, [thisArg])`
Executes a function for each item in the list, from head to tail.
- **Parameters:**
- `fn(data, item, list)`: Function to execute for each item.
- `thisArg` (optional): Value to use as `this` when executing `fn`.
```js
list.forEach((node, item, list) => {
console.log(node.type);
});
```
### `forEachRight(fn, [thisArg])`
Executes a function for each item in the list, from tail to head.
```js
list.forEachRight((node, item, list) => {
console.log(node.type);
});
```
### `reduce(fn, initialValue, [thisArg])`
Applies a function against an accumulator and each item to reduce it to a single value.
- **Parameters:**
- `fn(accumulator, data, item, list)`: Function to execute on each item.
- `initialValue`: Initial value for the accumulator.
- `thisArg` (optional): Value to use as `this` when executing `fn`.
```js
const total = list.reduce((sum, node) => sum + node.value, 0);
```
### `reduceRight(fn, initialValue, [thisArg])`
Same as `reduce`, but from tail to head.
```js
const total = list.reduceRight((sum, node) => sum + node.value, 0);
```
### `some(fn, [thisArg])`
Tests whether at least one element in the list passes the test implemented by `fn`.
- **Parameters:**
- `fn(data, item, list)`: Function to test for each element.
- `thisArg` (optional): Value to use as `this` when executing `fn`.
- **Returns:** `true` if the callback returns a truthy value for any item; otherwise, `false`.
```js
const hasTypeA = list.some(node => node.type === 'TypeA');
```
### `map(fn, [thisArg])`
Creates a new `List` with the results of calling a function on every element.
- **Parameters:**
- `fn(data, item, list)`: Function that produces an element of the new list.
- `thisArg` (optional): Value to use as `this` when executing `fn`.
- **Returns:** A new `List` instance.
```js
const mappedList = list.map(node => ({ ...node, value: node.value * 2 }));
```
### `filter(fn, [thisArg])`
Creates a new `List` with all elements that pass the test implemented by `fn`.
- **Parameters:**
- `fn(data, item, list)`: Function to test each element.
- `thisArg` (optional): Value to use as `this` when executing `fn`.
- **Returns:** A new `List` instance.
```js
const filteredList = list.filter(node => node.isActive);
```
### `nextUntil(startItem, fn, [thisArg])`
Iterates over the list starting from `startItem`, moving forward, until `fn` returns `true`.
- **Parameters:**
- `startItem`: The item to start from.
- `fn(data, item, list)`: Function to execute for each item.
- `thisArg` (optional): Value to use as `this` when executing `fn`.
```js
list.nextUntil(someItem, (node, item) => {
if (node.type === 'StopType') return true;
// Process node
});
```
### `prevUntil(startItem, fn, [thisArg])`
Iterates over the list starting from `startItem`, moving backward, until `fn` returns `true`.
```js
list.prevUntil(someItem, (node, item) => {
if (node.type === 'StartType') return true;
// Process node
});
```
## Mutation Methods
### `clear()`
Removes all items from the list.
```js
list.clear();
```
### `copy()`
Creates a shallow copy of the list.
- **Returns:** A new `List` instance.
```js
const newList = list.copy();
```
### `prepend(item)`
Inserts an item at the beginning of the list.
- **Parameters:**
- `item`: The item to prepend.
```js
const item = List.createItem(node);
list.prepend(item);
```
### `prependData(data)`
Creates a new item with the provided data and inserts it at the beginning.
```js
list.prependData(node);
```
### `append(item)`
Inserts an item at the end of the list.
```js
const item = List.createItem(node);
list.append(item);
```
### `appendData(data)`
Creates a new item with the provided data and inserts it at the end.
```js
list.appendData(node);
```
### `insert(item, [before])`
Inserts an item into the list before the specified item.
- **Parameters:**
- `item`: The item to insert.
- `before` (optional): The item before which the new item will be inserted. If `null` or not provided, the item is appended to the end.
```js
const item = List.createItem(node);
list.insert(item, existingItem);
```
### `insertData(data, [before])`
Creates a new item with the provided data and inserts it before the specified item.
```js
list.insertData(node, existingItem);
```
### `remove(item)`
Removes an item from the list.
- **Parameters:**
- `item`: The item to remove.
- **Returns:** The removed item.
```js
list.remove(existingItem);
```
### `push(data)`
Appends data to the end of the list (alias for `appendData`).
```js
list.push(node);
```
### `pop()`
Removes and returns the last item of the list.
- **Returns:** The removed item, or `null` if the list is empty.
```js
const lastItem = list.pop();
```
### `unshift(data)`
Prepends data to the beginning of the list (alias for `prependData`).
```js
list.unshift(node);
```
### `shift()`
Removes and returns the first item of the list.
- **Returns:** The removed item, or `null` if the list is empty.
```js
const firstItem = list.shift();
```
### `prependList(otherList)`
Inserts all items from `otherList` at the beginning of the list.
- **Parameters:**
- `otherList`: The list to prepend. After the operation, `otherList` will be empty.
```js
list.prependList(anotherList);
```
### `appendList(otherList)`
Inserts all items from `otherList` at the end of the list.
```js
list.appendList(anotherList);
```
### `insertList(otherList, [before])`
Inserts all items from `otherList` into the list before the specified item.
- **Parameters:**
- `otherList`: The list to insert. After the operation, `otherList` will be empty.
- `before` (optional): The item before which to insert the new list.
```js
list.insertList(anotherList, existingItem);
```
### `replace(oldItem, newItemOrList)`
Replaces `oldItem` with a new item or list.
- **Parameters:**
- `oldItem`: The item to replace.
- `newItemOrList`: The new item or list to insert.
**Example (with a single item):**
```js
const newItem = List.createItem(newNode);
list.replace(oldItem, newItem);
```
**Example (with a list):**
```js
const newList = new List().fromArray([node1, node2]);
list.replace(oldItem, newList);
```
## Array Compatibility
The `List` class is compatible with arrays in many cases. It provides methods to convert to and from arrays, and implements iterable protocols.
**Conversion to Array:**
```js
const array = list.toArray();
```
**Conversion from Array:**
```js
list.fromArray([node1, node2, node3]);
```
**Iteration using `for...of`:**
```js
for (const node of list) {
// Process node
}
```
**Note:** Direct index access (e.g., `list[0]`) is not supported.
## Serialization
The `List` class implements `toJSON()`, allowing it to be serialized with `JSON.stringify()`.
```js
const jsonString = JSON.stringify(list);
```
|