为了账号安全,请及时绑定邮箱和手机立即绑定

迭代器模式

迭代器模式

提供一种方法,可以顺序访问一个聚合对象中的各个元素,而又不暴露该对象的内部表示,就叫做迭代器模式。
绝大部分程序语言都内置了迭代器,比如 ES5 的 forEach 等,ES6 更是为 Array、Map、Set以及类数组对象提供了统一的迭代器接口,使用 for...of 循环便会默认调用该接口。

应用场景

由于绝大部分程序语言都内置了迭代器,所以我们没有必要去自己写一个,除非我们想要手动控制迭代的过程或顺序,用来满足更加多变的需求。
比如我们想要创建一个迭代器,能够访问数据集合的第一个、最后一个、前一个、后一个、当前这个、某一个以及倒序的功能。

例子:

const Iterator = (list) => {
  // 当前索引值,默认为第一个
  let current = 0;

  // 第一个
  const first = () => {
    return list[0];
  };

  // 最后一个
  const last = () => {
    return list[list.length - 1];
  };

  // 前一个
  const pre = () => {
    current -= 1;
    // 如果当前是第一个,则返回 undefined
    if (current < 0) {
      current = 0;
      return;
    }
    // 否则返回前一个
    return list[current];
  };

  // 后一个
  const next = () => {
    current += 1;
    // 如果当前是最后一个,则返回 undefined
    if (current === list.length) {
      current = list.length - 1;
      return;
    }
    // 否则返回后一个
    return list[current];
  };

  // 当前这个
  const cur = () => {
    return list[current];
  };

  // 某一个
  const nth = (index) => {
    // 如果索引值在数组长度范围内,则返回相应值
    if (index >= 0 && index < list.length) {
      return list[index];
    }
    // 否则返回 undefined
    return;
  };

  // 倒序
  const reverse = () => {
    const _arr = [];
    for (let i = list.length - 1; i >= 0; i--) {
      _arr.push(list[i]);
    }
    return _arr;
  };

  return {
    first,
    last,
    pre,
    next,
    cur,
    nth,
    reverse,
  };
};

// 测试代码
const arr = ['a', 'b', 'c', 'd'];
const iterator = Iterator(arr);

console.log(iterator.first()); // a
console.log(iterator.last()); // d
console.log(iterator.next()); // b
console.log(iterator.next()); // c
console.log(iterator.pre()); // b
console.log(iterator.cur()); // b
console.log(iterator.nth(3)); // d
console.log(iterator.reverse()); // ["d", "c", "b", "a"]

如有错误,欢迎指正,本人不胜感激。

点击查看更多内容
2人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消