[问题] javascript 函数式写法的状态传递

楼主: art1 (人,原来不是人)   2018-10-28 21:16:10
当初看到的贪食蛇专案 https://www.youtube.com/watch?v=bRlvGoWz6Ig
https://github.com/chrokh/fp-games/tree/master/001-snake
最让我疑惑不解的是关于下次状态的移动方向程式码
用来把使用者输入的方向加入伫列后回传新状态的是这段程式码
const enqueue = (state, move) => validMove(move)(state)
? merge(state)({ moves: state.moves.concat([move]) })
: state
然后取出伫列中的方向的是这一段
const nextMoves = state =>
state.moves.length > 1 ? dropFirst(state.moves) : state.moves
dropFirst 是作者自订的函式,目的是为了让取出第一个元素的语义更清楚
const dropFirst = xs => xs.slice(1)
这边是使用不会改变原阵列的 slice 函式
疑惑的点是,既然不会改变原阵列,那随着输入的方向越来越多,岂不是永远不会减少?
可是看影片没有这种情况
如果说是因为 nextMoves 这个函式让每个新状态的 moves 都只剩一个元素,那又是怎
么让 moves 内存有三个以上的方向,且使用者也不再进行输入(所以不会触发 enqueue
函式)时,让 moves 剩下的方向可以保留到下次的新状态呢?

Links booklink

Contact Us: admin [ a t ] ucptt.com