当你在使用Vuex、Redux、Pinia的时候,别人已经开始手写状态机了(中)

当你在使用Vuex、Redux、Pinia的时候,别人已经开始手写状态机了(中)

大家好,我是每天坚持一点点的铁蛋儿,一个爱分享前端的老body。这篇是分享手写状态机,大家务必点赞收藏保存一下慢慢看,你们的关注是我更新的动力。

相关学习资源

本系列有配套视频,大家学习同时千万不要忘了三连 + 关注 + 分享,有道是喝水不忘挖井人~

正文

以拖拽为例,如图所示:

1

  • 如上图中的转换结构需要四个参数:

    • S (初始状态)
    • A(触发行为)
    • Fn(关联操作)
    • S(结束状态)
  • state

     enum States {
       Start,
       DragStart,
       Moving,
       Stoped,
       Selected
     }
    复制代码
  • action触发行为

     enum Actions {
       AUTO,
       EvtDragStart,
       EvtDrag,
       EvtDragEnd,
     }
    复制代码
  • 代码如下

     // 状态操作函数
     type fn= (...args: Array<any>) => void
     // 状态机
     export default class StateMachine<S extends number, A extends number>{
       // 初识状态
       s: S
       // 转换结构
       table: Map<S, Map<A, [fn, S]>>
       constructor(initState: S) {
         this.s = initState
         this.table = new Map()
       }
       // 状态转换函数 
       register(from: S,action: A, fn: fn,to: S) {
         if (!this.table.has(from)) {
           this.table.set(from, new Map())
         }
         const getState = this.table.get(from)!
         getState.set(action, [fn, to])
       }
       // dispatch 派发action 执行fn
       dispatch(action: A, ...data: Array<any>) {
         // 获取初始的table
         const initTable = this.table.get(this.s)
         if (!initTable) {
           return false
         }
         if (!initTable.has(action)) {
           return false
         }
         // 获取action对应fn和newState
         const [fn, newState] = initTable.get(action)!
         fn(...data)
         this.s = newState
         // 主要是给AUTO状态使用 所以while成自动状态
         while (this.dispatch("<auto>" as A, ...data));
         return true
       }
     }
    复制代码

    未完待续。。。。。。。

我是每天坚持进步一点点的铁蛋儿,如果你对技术有像一素的偏执,欢迎【小破站】前端铁蛋儿或者vx:15910703837一起学习一起进步。

分类:
前端
标签: