坚持造轮子第五天 - 时间旅行

9,588 阅读2分钟

🔽🔽🔽🔽🔽🔽🔽�老胡讲代码🔽🔽🔽🔽🔽🔽

www.bilibili.com/video/BV1Tr…

⏫⏫⏫⏫⏫⏫⏫⏫⏫⏫⏫⏫⏫⏫⏫⏫⏫⏫⏫⏫

二话不说 轮子我都会造 还怕你面试问吗? 一天造一个轮子,干就完了。

看点

  • 针对大厂笔试、面试必考手写题目
  • TDD方式开发
  • 配合视频讲解

造轮子计划

(计划赶不上变化 随时迭代 欢迎留言 随时摸鱼)

  • 框架基础
  • JS基础
    • Promise.all/race
    • 路由
    • new
    • call/apply/bind
    • Object.create
    • 深拷贝、浅拷贝
  • 算法、设计模式
    • 二分查找

    • 快排

    • 二分查找

    • 冒泡排序

    • 选择排序

    • 订阅发布

    • 斐波那契算法

    • 去重

时间旅行

时间旅行就是让程序可以在自己历史状态里面任意穿梭,想想Office和PS软件中的Undo和Redo就知道。再想想王者荣耀的录像功能。

时间旅行实际上就是设计模式中的备忘录模式。这个到我们可以练习设计模式的时候再升华,先不在这里强行渡劫。

首先Redux为时间旅行做了基础性工作,首先所有组件上缴了状态,地主家不存余粮,然后使用纯函数加工数据,不存在秘方和小料,保证了加工结果的可预测性。

然后要做的就是找一个容器我们可以叫做历史和时间轴,把状态变更的历史存储起来。把状态分为三个时间段:

  • 过去 (过去状态数组)
  • 现在(只有一个状态)
  • 将来 (将来状态数组)
  • gotoState 函数则是用来做时间旅行的,把过去、现在、将来重新分配

需求

1. UNDO

it("前进undo ", () => {
    const history = createHistory()

    history.push({num: 1})
    history.push({num: 2})
    history.push({num: 3})
    history.undo()
    expect(history.present.num).toBe(2)
  });

2. REDO

it("回退redo ", () => {
    const history = createHistory()

    history.push({num: 1})
    history.push({num: 2})
    history.push({num: 3})
    history.push({num: 4})
    history.undo()
    history.undo()
    history.undo()
    history.redo()
    expect(history.present.num).toBe(2)
  });

3. 定点漂移

it("定点回退 ", () => {
    const history = createHistory()

    history.push({num: 1})
    history.push({num: 2})
    history.push({num: 3})
    history.gotoState(1)
    expect(history.present.num).toBe(2)
  });

功能实现

超级简单是吧 我就不解释了

module.exports = createHistory = () => {
  const timeline = {};

  timeline.past = [];
  timeline.futrue = [];

  timeline.gotoState = (index) => {
    const allState = [...timeline.past, timeline.present, ...timeline.futrue];
    timeline.present = allState[index];
    timeline.past = allState.slice(0, index);
    timeline.futrue = allState.slice(index + 1, allState.length);
  };

  timeline.getIndex = () => {
    // 获取当前状态index
    return timeline.past.length;
  };

  // 保存当前状态
  timeline.push = (currentState) => {
    // 将状态都保存,并更新当前状态
    if (timeline.present) {
      timeline.past.push(timeline.present);
    }
    timeline.present = currentState;
  };

  // 后退
  timeline.undo = () => {
    if (timeline.past.length !== 0) {
      timeline.gotoState(timeline.getIndex() - 1);
    }
  };

  // 前进
  timeline.redo = () => {
    if (timeline.futrue.length !== 0) {
      timeline.gotoState(timeline.getIndex() + 1);
    }
  };

  return timeline;
};

测试

OK 任务完成

关注全栈然叔 带你坚持天天造轮子 (周末休息 拒绝996)

源码地址

>>>>>>>>>>>>>>>【源码地址】 <<<<<<<<<<<<<<<<

本文使用 mdnice 排版