/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
'use strict';

/**
 * Implements the iterator protocol.
 * Given a string and a substring, will be able to iterate
 * and return all found instances of the substring.
 */
class SubstringFinder {
  constructor(string, substring) {
    this.string = string;
    this.substring = substring;
    this.index = 0;
  }

  /**
   * Implements iterable protocol.
   * Finds occurrences of one string in another string and returns
   * tuples which specify [starting, ending] indices of match.
   */
  [Symbol.iterator]() {
    return {
      next: function() {
        // Get the index of the next occurrence,
        const next = this.string.indexOf(this.substring, this.index);
        // and reset index based on result.
        this.index = 0 <= next ? next + this.substring.length : next;

        return this.index < 0
          ? { done: true, value: null }
          : { done: false, value: this.getTuple(next) };
      }.bind(this)
    };
  }

  /**
   * Returns a tuple based on the given index and the length if substring
   * @param   {Number}   index The first tuple value.
   * @returns {Number[]}
   */
  getTuple(index) {
    return [index, index + this.substring.length - 1];
  }
}

module.exports = SubstringFinder;
