Guest User

Untitled

a guest
Feb 19th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. const createStore = (reducer, preloadedState) => {
  2. return {
  3. currentState: preloadedState,
  4.  
  5. getState() {
  6. return this.currentState
  7. },
  8.  
  9. dispatch(action) {
  10. this.currentState = reducer(this.currentState, action)
  11. }
  12. }
  13. }
  14.  
  15. const INITIAL_STATE = {
  16. left: false,
  17. right: false,
  18. x: 0
  19. }
  20.  
  21. const TICK = Symbol("tick")
  22. const LEFT_ON = Symbol("left_on")
  23. const LEFT_OFF = Symbol("left_off")
  24. const RIGHT_ON = Symbol("right_on")
  25. const RIGHT_OFF = Symbol("right_off")
  26.  
  27. const reducer = (state, action) => {
  28. switch (action.type) {
  29. case TICK:
  30. return {
  31. ...state,
  32. x: (state => {
  33. if (state.left && !state.right) {
  34. return state.x - 1
  35. } else if (!state.left && state.right) {
  36. return state.x + 1
  37. } else {
  38. return state.x
  39. }
  40. })(state)
  41. }
  42. break
  43. case LEFT_ON:
  44. return {
  45. ...state,
  46. left: true
  47. }
  48. break
  49. case LEFT_OFF:
  50. return {
  51. ...state,
  52. left: false
  53. }
  54. case RIGHT_ON:
  55. return {
  56. ...state,
  57. right: true
  58. }
  59. break
  60. case RIGHT_OFF:
  61. return {
  62. ...state,
  63. right: false
  64. }
  65. default:
  66. return state
  67. }
  68. }
  69.  
  70. const store = createStore(reducer, INITIAL_STATE)
  71.  
  72. const tickAction = time => {
  73. return {
  74. type: TICK,
  75. time: time
  76. }
  77. }
  78.  
  79. const leftOnAction = _ => {
  80. return {
  81. type: LEFT_ON
  82. }
  83. }
  84.  
  85. const leftOffAction = _ => {
  86. return {
  87. type: LEFT_OFF
  88. }
  89. }
  90.  
  91. const rightOnAction = _ => {
  92. return {
  93. type: RIGHT_ON
  94. }
  95. }
  96.  
  97. const rightOffAction = _ => {
  98. return {
  99. type: RIGHT_OFF
  100. }
  101. }
  102.  
  103. const tick = (store, time) => {
  104. document.body.textContent = JSON.stringify(store.getState())
  105. store.dispatch(tickAction(time))
  106. requestAnimationFrame(time => tick(store, time))
  107. }
  108. tick(store, 0)
  109.  
  110. addEventListener("keydown", event => onKeydown(store, event))
  111. addEventListener("keyup", event => onKeyup(store, event))
  112.  
  113. const onKeydown = (store, event) => {
  114. switch (event.key) {
  115. case "ArrowLeft":
  116. store.dispatch(leftOnAction())
  117. break
  118. case "ArrowRight":
  119. store.dispatch(rightOnAction())
  120. break
  121. }
  122. }
  123.  
  124. const onKeyup = (store, event) => {
  125. switch (event.key) {
  126. case "ArrowLeft":
  127. store.dispatch(leftOffAction())
  128. break
  129. case "ArrowRight":
  130. store.dispatch(rightOffAction())
  131. break
  132. }
  133. }
Add Comment
Please, Sign In to add comment