Categories
interview

Multi List Iterator – Javascript

Print a list of lists vertically using an Iterator.

For example:

// Usage
const node = new MultiIterator([[1, 2], [], [4], [5]]);

while (node.hasNext()) {
  console.log(node.next());
}

Input:

[[1, 2], [], [4], [5]]

Output:

1

4

5

2
class MultiIterator {
  constructor(inp) {
    this.inp = inp;
    this.x = -1;
    this.inpLen = inp.length;
    this.levelProgress = Array(inp.length).fill(0);
    this.nextX = 0;
  }

  hasNext() {
    var count = 0;
    var listIndex = this.x;
    var elemIndex;
    do {
      listIndex++;
      listIndex %= this.inpLen;
      elemIndex = this.levelProgress[listIndex]; // index = size - 1
      count++;
    } while (count < this.inpLen && elemIndex === this.inp[listIndex].length)
    if (elemIndex === this.inp[listIndex].length) {
      return false;
    }
    this.nextX = listIndex;
    return true;
  }

  next() {
    if (this.hasNext()) {
      this.x = this.nextX;
      this.levelProgress[this.x]++;
      return this.inp[this.x][this.levelProgress[this.x] - 1];
    }
    return null;
  }
}

// Test Code
const node = new MultiIterator([
  [1, 2],
  [],
  [4],
  [5],
]);

while (node.hasNext()) {
  console.log(node.next());
}

Demo

You can print this list horizontally as well.

For example:

Input:

[[1, 2], [], [4], [5]]

Output:

1

2

4

5
class MultiIterator {
  constructor(inp) {
    this.inp = inp;
    this.x = 0;
    this.y = -1;
    this.inpLen = inp.length;
    this.nextX = 0;
    this.nextY = 0;
  }

  hasNext() {
    var listIndex = this.x;
    var elemIndex = this.y + 1;
    while (listIndex < this.inpLen && elemIndex === this.inp[listIndex].length) {
      listIndex++;
      elemIndex = 0;
    }
    if (listIndex === this.inpLen) {
      return false;
    }
    this.nextX = listIndex;
    this.nextY = elemIndex;
    return true;
  }

  next() {
    if (this.hasNext()) {
      this.x = this.nextX;
      this.y = this.nextY;
      return this.inp[this.nextX][this.nextY];
    }
    return null;
  }
}

// Test Code
const node = new MultiIterator([
  [1, 2],
  [],
  [4],
  [5],
]);

while (node.hasNext()) {
  console.log(node.next());
}

Demo