Created
July 28, 2020 12:32
-
-
Save frankiesardo/41632f93c0993135aaa1e5c385fe9a02 to your computer and use it in GitHub Desktop.
Memory game
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import './App.css'; | |
const actionType = { | |
SHOW: "show", | |
HIDE: "hide" | |
} | |
function reducer(state, action) { | |
let payload = action.payload | |
switch (action.type) { | |
case actionType.SHOW: | |
return [ | |
...state.slice(0, payload), | |
{ | |
...state[payload], | |
status: "visible" | |
}, | |
...state.slice(payload + 1)] | |
case actionType.HIDE: | |
return [ | |
...state.slice(0, payload), | |
{ | |
...state[payload], | |
status: "hidden" | |
}, | |
...state.slice(payload + 1)] | |
default: | |
throw action | |
} | |
} | |
function http(dispatch, { callback, url, params }) { | |
setTimeout(function () { | |
console.log(`Calling server.. url: ${url} params: ${JSON.stringify(params)}`); | |
dispatch( | |
{ | |
type: callback, | |
payload: { | |
success: true, | |
status: 200, | |
body: { profile: { name: "Alice" } } | |
} | |
}) | |
}, 1000) | |
} | |
function log(dispatch, payload) { | |
console.log(`Logging.. ${JSON.stringify(payload)}`) | |
} | |
const handlers = { log: log, http: http } | |
const cards = ["♠", "♥️", "♣️", "♦"] | |
const cover = "🃏" | |
const initialState = [...cards, ...cards].sort(() => Math.random() - 0.5).map((emoji, index) => { return { emoji: emoji, index: index, status: "hidden" } }) | |
const DispatchContext = React.createContext(); | |
const Card = React.memo(({ state }) => { | |
let dispatch = React.useContext(DispatchContext) | |
let dispatchShow = () => dispatch({ type: actionType.SHOW, payload: state.index }) | |
let dispatchHide = () => dispatch({ type: actionType.HIDE, payload: state.index }) | |
if (state.status === "hidden") { | |
return <li onClick={dispatchShow}>{cover}</li> | |
} else { | |
return <li onClick={dispatchHide}>{state.emoji}</li> | |
} | |
}) | |
const Home = React.memo(({ state }) => { | |
return <ol> {state.map(x => <Card state={x}> </Card>)}</ol> | |
}) | |
function App() { | |
const [state, dispatch] = React.useReducer(reducer, initialState) | |
return ( | |
<DispatchContext.Provider value={dispatch}> | |
<Home state={state} /> | |
</DispatchContext.Provider> | |
) | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment