|
548 | 548 | return this; |
549 | 549 | } |
550 | 550 |
|
| 551 | + /** |
| 552 | + * Function that calls a function for each element in the collection and returns an array with the |
| 553 | + * results of the calls to the function. The function will receive two parameters: callback(index, element) |
| 554 | + * where <index> is the index of the element in the collection and <element> is the element itself. The function |
| 555 | + * is bound to the collection, so that this[index] will be the element. |
| 556 | + * @param {*} callback: the function to call for each element in the collection |
| 557 | + * @returns an array with the results of the calls to the function |
| 558 | + */ |
| 559 | + $.map = function(callback) { |
| 560 | + let result = []; |
| 561 | + callback = callback.bind(this); |
| 562 | + for (let i = 0; i < this.length; i++) { |
| 563 | + result.push(callback(i, this[i])); |
| 564 | + } |
| 565 | + return result; |
| 566 | + } |
| 567 | + |
| 568 | + /** |
| 569 | + * Function that filters the elements in the collection that return "true"-ish when calling the callback function. |
| 570 | + * The callback function will receive two parameters: callback(index, element) where <index> is the index of the |
| 571 | + * element in the collection and <element> is the element itself. The function is bound to the collection, so that |
| 572 | + * this[index] will be the element. |
| 573 | + * The callback function should return true if the element passes the filter, false otherwise. |
| 574 | + * @param {*} callback: the function to filter the elements in the collection |
| 575 | + * @returns a new collection with the elements that pass the filter |
| 576 | + */ |
| 577 | + $.filter = function(callback) { |
| 578 | + let result = []; |
| 579 | + callback = callback.bind(this); |
| 580 | + for (let i = 0; i < this.length; i++) { |
| 581 | + if (callback(i, this[i])) { |
| 582 | + result.push(this[i]); |
| 583 | + } |
| 584 | + } |
| 585 | + return $(result); |
| 586 | + } |
| 587 | + |
| 588 | + /** |
| 589 | + * Function that retrieves the text of the first element in the collection, or sets the text of all the elements |
| 590 | + * @param {*} text: the text to set for the elements |
| 591 | + * @returns the text of the first element in the collection or the collection of objects |
| 592 | + */ |
| 593 | + $.text = function(text) { |
| 594 | + if (text === undefined) { |
| 595 | + return this[0].innerText; |
| 596 | + } |
| 597 | + this.forEach((x) => x.innerText = text); |
| 598 | + return this; |
| 599 | + } |
| 600 | + |
551 | 601 | /** |
552 | 602 | * The $ function scoped to the objects that are part of a previous $ object; this is the same |
553 | 603 | * function $(...elements), except for the fact that the search for elements using selectors |
|
0 commit comments