Javascript嵌套数组通过Iterator和hasnext及下一个实现进行展平

时间:2019-02-26 23:43:42

标签: javascript algorithm iterator

**试图实现一个具有next和hasNext两个方法的类,我能够在C ++和Java中找到类似的实现,但是没有Javascript,那么任何帮助都将受到赞赏**


class NestedIterator {
  constructor() {}

hasNext() {
   //Todo
  }

  next() {
    //Todo
   }
}

var list;
var iterator;

/* Should print
 * 2
 * 4
 * 6
 */
list = [2, [4, [6]]];
iterator = new NestedIterator(list);
while (iterator.hasNext()) {
  console.log(iterator.next());
}`

1 个答案:

答案 0 :(得分:2)

此方法首先将数组展平,然后在展平的数组上循环。

class NestedIterator {
  constructor(list) {
    this.list = [];

    let flat = (arr, index) => {
      if (index === arr.length) return;
      
      if (Array.isArray(arr[index])) flat(arr[index], 0);
      else this.list.push(arr[index]);
      
      flat(arr, ++index);
    }

    this.index = 0;
    flat(list, 0);
    this.length = this.list.length;
  }

  hasNext() {
    return this.index < this.length;
  }

  next() {
    if (this.hasNext()) return this.list[this.index++];
    else return null; // maybe an error.
  }
}

var list;
var iterator;

/* Should print
 * 2
 * 4
 * 6
 */
list = [2, [4, [6]]];
iterator = new NestedIterator(list);
while (iterator.hasNext()) {
  console.log(iterator.next());
}