javascript increment alphabet 1

javascript increment alphabet

class StringIdGenerator {
  constructor(chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
    this._chars = chars;
    this._nextId = [0];
  }

  next() {
    const r = [];
    for (const char of this._nextId) {
      r.unshift(this._chars[char]);
    }
    this._increment();
    return r.join('');
  }

  _increment() {
    for (let i = 0; i < this._nextId.length; i++) {
      const val = ++this._nextId[i];
      if (val >= this._chars.length) {
        this._nextId[i] = 0;
      } else {
        return;
      }
    }
    this._nextId.push(0);
  }

  *[Symbol.iterator]() {
    while (true) {
      yield this.next();
    }
  }
}

Here is what the above code is Doing:
1. We create a class called StringIdGenerator.
2. We create a constructor that takes a string of characters as an argument.
3. We create a property called _chars that stores the string of characters.
4. We create a property called _nextId that stores an array of numbers.
5. We create a method called next that returns a string of characters.
6. We create a method called _increment that increments the array of numbers.
7. We create a generator function that returns an infinite loop of strings.

Similar Posts