All files / src/iterators Iterator.js

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    408x 2x   406x 1x     405x       73x       35x       11x 2x   9x 2x     7x 7x 32x     7x      
export default class Iterator {
  constructor(arr) {
    if (!arr) {
      throw new Error('Iterable array is null or undefined');
    }
    if (!(arr instanceof Array || arr instanceof Iterator)) {
      throw new Error('Invalid array type');
    }
 
    this.arr = arr;
  }
 
  [Symbol.iterator]() {
    return this.arr[Symbol.iterator]();
  }
 
  toArray() {
    return Array.from(this);
  }
 
  toMap(keySelector, valueSelector) {
    if (typeof keySelector !== 'function') {
      throw new Error('KeySelector must be a function.');
    }
    if (typeof valueSelector !== 'function') {
      throw new Error('ValueSelector must be a function.');
    }
 
    let map = new Map();
    for (let item of this) {
      map.set(keySelector(item), valueSelector(item));
    }
 
    return map;
  }
}