我的github源码:https://github.com/shangyueyue/ssy-utils/blob/master/src/basetheory/generator.js

一、实现迭代器

function read(books) {
  let index = 0;
  return {
    next() {
      const done = index === books.length;
      const value = done ? undefined : books[index++]; // eslint-disable-line
      return {
        value,
        done,
      };
    },
  };
}
const it = read(['nodejs', 'css', 'js']);
let result;
do {
  result = it.next();
  console.log(result);
} while (!result.done);

二、gennerator 迭代

function* func(subjects) {
  let result;
  for (const item of subjects) {
    result = yield item;
    console.log(result);
  }
}
const subjects = ['js', 'html5', 'css'];
const iterater = func(subjects);
console.log(iterater.next());
console.log(iterater.next(9));
console.log(iterater.next(0));

三、递归遍历

function* flat(arr) {
  for (const item of arr) {
    if (Array.isArray(item)) {
      yield* flat(item);
    } else {
      yield item;
    }
  }
}
const arr = [1, [[2, 3], 4], [5, 6]];
const iterator = flat(arr);
let result;
do {
  result = iterator.next();
  console.log(result);
} while (!result.done);

三、symbal iterator 遍历

function* arrGenerator() {
  for (let i = 0; i < this.length; i++) {
    yield this[i] + 5;
  }
}
const arr = [1, 3, 4, 5];
arr[Symbol.iterator] = arrGenerator;
// const iterator = arrGenerator(arr);
for (const item of arr) {
  console.log(item);
}

实现对象的 for of

function* objGenerator() {
  for (const item of Object.keys(this)) {
    const key = item;
    const value = this[item];
    yield [key, value];
  }
}

const obj = {
  name: 'shangyueyue',
  age: 18,
};
obj[Symbol.iterator] = objGenerator;
for (const [key, value] of obj) {
  console.log(key, value);
}

 

转载于:https://www.cnblogs.com/shangyueyue/p/10873680.html

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐