All files / src/utils DOM-utils.ts

100% Statements 16/16
100% Branches 2/2
100% Functions 5/5
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 622x   2x                 11x       11x   11x 835x         10x                     2x             837x   837x 2x     835x                   2x 11x   2x  
export const EXTRACT_NUMBER_ERROR = 'The given id is not valid: ';
 
export default class DOMUtils {
  /**
   * Extract numbers from ids of a node list.
   *
   * @param {string} stringToRemove
   * @param {NodeListOf<Element>} nodeList
   * @returns {number[]}
   * @memberof DOMUtils
   */
  public extractNumbersFromIdsOfNodes(
    stringToRemove: string,
    nodeList: NodeListOf<Element>
  ): number[] {
    let extractedNumbers: number[] = [];
 
    nodeList.forEach(element => {
      extractedNumbers.push(
        this.extractNumberFromId(stringToRemove, element.id)
      );
    });
 
    return extractedNumbers;
  }
 
  /**
   * Extract a number from a string.
   *
   * @param {string} stringToRemove
   * @param {string} id
   * @returns {number}
   * @memberof DOMUtils
   */
  public extractNumberFromId(stringToRemove: string, id: string): number {
    /* Don't use parseInt here
     * - parseInt('8azjzekhezka') return 8
     * - parseInt('hkjh8azehrza) return NaN
     * - Number('8azjzekhezka') return NaN
     * - Number('hkjh8azehrza) return NaN
    */
    let extractedNumber = Number(id.replace(stringToRemove, ''));
 
    if (Number.isNaN(extractedNumber)) {
      throw new Error(EXTRACT_NUMBER_ERROR + id);
    }
 
    return extractedNumber;
  }
 
  /**
   * Get all node that have an id that begin with a string.
   *
   * @param {string} string
   * @returns {NodeListOf<Element>}
   * @memberof DOMUtils
   */
  public getAllNodesWithIdThatBeginsWith(string: string): NodeListOf<Element> {
    return document.querySelectorAll('[id^=' + string + ']');
  }
}