Using map() on an iterator

后端 未结 8 1818
误落风尘
误落风尘 2021-02-01 11:59

Say we have a Map: let m = new Map();, using m.values() returns a map iterator.

But I can\'t use forEach() or map() o

8条回答
  •  南笙
    南笙 (楼主)
    2021-02-01 12:09

    You could retrieve an iterator over the iterable, then return another iterator that calls the mapping callback function on each iterated element.

    const map = (iterable, callback) => {
      return {
        [Symbol.iterator]() {
          const iterator = iterable[Symbol.iterator]();
          return {
            next() {
              const r = iterator.next();
              if (r.done)
                return r;
              else {
                return {
                  value: callback(r.value),
                  done: false,
                };
              }
            }
          }
        }
      }
    };
    
    // Arrays are iterable
    console.log(...map([0, 1, 2, 3, 4], (num) => 2 * num)); // 0 2 4 6 8
    

提交回复
热议问题