堅持造輪子第五天 - 時間旅行

🔽🔽🔽🔽🔽🔽🔽�老胡講代碼🔽🔽🔽🔽🔽🔽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 排版

相關文章
相關標籤/搜索