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

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

www.bilibili.com/video/BV1Tr…github

⏫⏫⏫⏫⏫⏫⏫⏫⏫⏫⏫⏫⏫⏫⏫⏫⏫⏫⏫⏫面试

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

看点

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

造轮子计划

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

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

    • 快排markdown

    • 二分查找app

    • 冒泡排序框架

    • 选择排序ide

    • 订阅发布

    • 斐波那契算法

    • 去重

时间旅行

时间旅行就是让程序能够在本身历史状态里面任意穿梭,想一想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 排版

相关文章
相关标签/搜索