Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const createStore = (reducer, preloadedState) => {
- return {
- currentState: preloadedState,
- getState() {
- return this.currentState
- },
- dispatch(action) {
- this.currentState = reducer(this.currentState, action)
- }
- }
- }
- const INITIAL_STATE = {
- left: false,
- right: false,
- x: 0
- }
- const TICK = Symbol("tick")
- const LEFT_ON = Symbol("left_on")
- const LEFT_OFF = Symbol("left_off")
- const RIGHT_ON = Symbol("right_on")
- const RIGHT_OFF = Symbol("right_off")
- const reducer = (state, action) => {
- switch (action.type) {
- case TICK:
- return {
- ...state,
- x: (state => {
- if (state.left && !state.right) {
- return state.x - 1
- } else if (!state.left && state.right) {
- return state.x + 1
- } else {
- return state.x
- }
- })(state)
- }
- break
- case LEFT_ON:
- return {
- ...state,
- left: true
- }
- break
- case LEFT_OFF:
- return {
- ...state,
- left: false
- }
- case RIGHT_ON:
- return {
- ...state,
- right: true
- }
- break
- case RIGHT_OFF:
- return {
- ...state,
- right: false
- }
- default:
- return state
- }
- }
- const store = createStore(reducer, INITIAL_STATE)
- const tickAction = time => {
- return {
- type: TICK,
- time: time
- }
- }
- const leftOnAction = _ => {
- return {
- type: LEFT_ON
- }
- }
- const leftOffAction = _ => {
- return {
- type: LEFT_OFF
- }
- }
- const rightOnAction = _ => {
- return {
- type: RIGHT_ON
- }
- }
- const rightOffAction = _ => {
- return {
- type: RIGHT_OFF
- }
- }
- const tick = (store, time) => {
- document.body.textContent = JSON.stringify(store.getState())
- store.dispatch(tickAction(time))
- requestAnimationFrame(time => tick(store, time))
- }
- tick(store, 0)
- addEventListener("keydown", event => onKeydown(store, event))
- addEventListener("keyup", event => onKeyup(store, event))
- const onKeydown = (store, event) => {
- switch (event.key) {
- case "ArrowLeft":
- store.dispatch(leftOnAction())
- break
- case "ArrowRight":
- store.dispatch(rightOnAction())
- break
- }
- }
- const onKeyup = (store, event) => {
- switch (event.key) {
- case "ArrowLeft":
- store.dispatch(leftOffAction())
- break
- case "ArrowRight":
- store.dispatch(rightOffAction())
- break
- }
- }
Add Comment
Please, Sign In to add comment