Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/next question #5

Merged
merged 4 commits into from
Mar 10, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 37 additions & 31 deletions src/actions/api.js
Original file line number Diff line number Diff line change
@@ -1,49 +1,55 @@
import request from 'superagent'
import { createBreedAndSubBreedList, createNextQuestion, sleep } from '../lib/utils'

export const SET_BREEDLIST = 'SET_BREEDLIST'
export const SET_QUESTION_IMG_URL = 'SET_QUESTION_IMG_URL'
export const GAME_STARTED = 'GAME_STARTED'
export const NEXT_QUESTION = 'NEXT_QUESTION'

export const fetchBreedList = () => {
export const startGame = () => {
return async (dispatch) => {
const response = await request('https://dog.ceo/api/breeds/list/all')
const allBreeds = response.body.message
const breeds = Object.keys(allBreeds)
const breedList = breeds.reduce((breedList, breed, _, breeds) => {
if(allBreeds[breed].length === 0){
return [...breedList, breed]
}

const subBreeds = allBreeds[breed].map(subBreed => `${subBreed}-${breed}`)

return [...breedList, ...subBreeds]
}, [])
const breedList = createBreedAndSubBreedList(response.body.message)

dispatch(setBreedList(breedList))
dispatch(gameStarted(breedList))
}
}

export const setBreedList = (breedList) => ({
type: SET_BREEDLIST, payload: breedList
})

export const fetchRandomImageFromBreed = (breed) => {
return async (dispatch) => {
let response

// We check to see if the breed is a subbreed
if(breed.includes('-')){
// if it is a sub breed the api endpoint is different
const [subBreed, superBreed] = breed.split('-')
response = await request(`https://dog.ceo/api/breed/${superBreed}/${subBreed}/images/random`)
} else {
response = await request(`https://dog.ceo/api/breed/${breed}/images/random`)
}

const url = response.body.message
dispatch(setQuestionImageUrl(url))
export const fetchRandomImageFromBreed = async (breed) => {
let response

// We check to see if the breed is a subbreed
if(breed.includes('-')){
// if it is a sub breed the api endpoint is different
const [subBreed, superBreed] = breed.split('-')
response = await request(`https://dog.ceo/api/breed/${superBreed}/${subBreed}/images/random`)
} else {
response = await request(`https://dog.ceo/api/breed/${breed}/images/random`)
}

return response.body.message
}

export const setQuestionImageUrl = (url) => ({
type: SET_QUESTION_IMG_URL, payload: url
})
export const gameStarted = (breedList) => ({
type: GAME_STARTED, payload: breedList
})

export const nextQuestionCreated = (question) => ({
type: NEXT_QUESTION, payload: question
})

export const nextQuestion = () => {
return async (dispatch, getState) => {
const { currentBreeds, correctAnswer } = createNextQuestion(getState().question.currentBreeds)
const imageUrl = await fetchRandomImageFromBreed(correctAnswer)

// Waiting a second so the user can see the feedback
await sleep(1000)

dispatch(nextQuestionCreated({ currentBreeds, correctAnswer, imageUrl }))
}
}
21 changes: 15 additions & 6 deletions src/containers/AnswerButton.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
import React from 'react'
import { black } from 'ansi-colors';
import { connect } from 'react-redux'
import { nextQuestion } from '../actions/api'

export default class AnswerButton extends React.Component {
const GREEN = '#90F636'
const RED = '#F53673'
const BLACK = 'black'

class AnswerButton extends React.Component {
state = {
textColor: black
textColor: BLACK
}

checkAnswer = (event) => {
if(event.target.innerText === this.props.correctAnswer){
this.setState({ textColor: '#90F636'})
this.setState({ textColor: GREEN })
this.props.nextQuestion()
} else {
this.setState({ textColor: '#F53673'})
this.setState({ textColor: RED })
}
}

Expand All @@ -27,4 +33,7 @@ export default class AnswerButton extends React.Component {
</button>
)
}
}
}

export default connect(null, { nextQuestion })(AnswerButton)

17 changes: 7 additions & 10 deletions src/containers/Game.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
import React, { PureComponent } from 'react'
import { connect } from 'react-redux'
import { shuffle, sampleSize, sample } from 'lodash/collection'
import { fetchBreedList } from '../actions/api'
import { startGame } from '../actions/api'
import Question from './Question'
import AnswerButton from './AnswerButton';

class Game extends PureComponent {
componentDidMount(){
this.props.fetchBreedList()
this.props.startGame()
}

render(){
const { breeds, correctAnswer, options } = this.props
if(breeds.length === 0) return <h1>Loading</h1>
if(breeds.length === 0 || options === null ) return <h1>Loading</h1>

return <>
<Question breed={correctAnswer} />
<Question />
{ options.map(option =>
<AnswerButton
key={`${option}-${Math.random()}`}
Expand All @@ -28,13 +27,11 @@ class Game extends PureComponent {
}

const mapStateToProps = state => {
const options = shuffle(sampleSize(state.breeds, 3))
const correctAnswer = sample(options)
return {
breeds: state.breeds,
options,
correctAnswer
options: state.question.currentBreeds,
correctAnswer: state.question.correctAnswer
}
}

export default connect(mapStateToProps, { fetchBreedList })(Game)
export default connect(mapStateToProps, { startGame })(Game)
7 changes: 4 additions & 3 deletions src/containers/Question.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import React, { PureComponent } from 'react'
import '../css/Question.css';
import { connect } from 'react-redux'
import { fetchRandomImageFromBreed } from '../actions/api'
import { nextQuestion } from '../actions/api'

class Question extends PureComponent {
componentDidMount(){
this.props.fetchRandomImageFromBreed(this.props.breed)
this.props.nextQuestion()
}

render(){
Expand All @@ -26,7 +26,8 @@ class Question extends PureComponent {
const mapStateToProps = state => {
return {
imageUrl: state.question.imageUrl,
correctAnswer: state.question.correctAnswer
}
}

export default connect(mapStateToProps, { fetchRandomImageFromBreed })(Question)
export default connect(mapStateToProps, { nextQuestion })(Question)
36 changes: 36 additions & 0 deletions src/lib/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { shuffle, sample, sampleSize } from 'lodash/collection'

export const createBreedAndSubBreedList = (allBreeds) => {
const breeds = Object.keys(allBreeds)
const breedList = breeds.reduce((breedList, breed) => {
if(allBreeds[breed].length === 0){
return [...breedList, breed]
}

const subBreeds = allBreeds[breed].map(subBreed => `${subBreed}-${breed}`)

return [...breedList, ...subBreeds]
}, [])

return breedList
}

export const sleep = (duration) => new Promise((resolve) => {
setTimeout(() => {
resolve();
}, duration)
})

export const createSelection = (breedList, breedCount) => {
const currentBreeds = shuffle(sampleSize(breedList, breedCount))
return {
currentBreeds,
}
}

export const createNextQuestion = (currentBreeds) => {
return {
correctAnswer: sample(currentBreeds),
currentBreeds: shuffle(currentBreeds)
}
}
23 changes: 17 additions & 6 deletions src/reducers/question.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,26 @@
import { SET_QUESTION_IMG_URL } from "../actions/api";
import { GAME_STARTED, NEXT_QUESTION } from "../actions/api";
import { createSelection } from '../lib/utils'

const initialState = {
imageUrl: null
imageUrl: null,
currentBreeds: null,
correctAnswer: null,
breedCount: 3
}

export default (state = initialState, action = {}) => {
switch (action.type) {
case SET_QUESTION_IMG_URL:
return { ...state, imageUrl: action.payload}

default:
case GAME_STARTED: {
const { currentBreeds } = createSelection(action.payload, state.breedCount)
return { ...state, currentBreeds }
}
case NEXT_QUESTION: {
const { currentBreeds, correctAnswer, imageUrl } = action.payload
return { ...state, currentBreeds, correctAnswer, imageUrl }
}

default: {
return state
}
}
}
35 changes: 27 additions & 8 deletions src/tests/questionReducer.test.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,39 @@
import questionReducer from '../reducers/question'
import { SET_QUESTION_IMG_URL } from '../actions/api';
import { NEXT_QUESTION, GAME_STARTED } from '../actions/api';

it('Sets a new image url in resonse to SET_QUESTION_IMG_URL', () => {
const url = "https://images.dog.ceo/breeds/kelpie/n02105412_7514.jpg"
it('Sets a Question in response to NEXT_QUESTION', () => {
const payload = {
imageUrl: "https://images.dog.ceo/breeds/kelpie/n02105412_7514.jpg",
currentBreeds: ['shiba', 'akita', 'kelpie'],
correctAnswer: 'kelpie'
}
const action = {
type: SET_QUESTION_IMG_URL,
payload: url
type: NEXT_QUESTION,
payload
}

const newState = questionReducer({}, action)
const newState = questionReducer(undefined, action)

expect(newState.imageUrl).toStrictEqual(url)
expect(newState).toMatchObject(payload)
});

it('Sets currenBreeds to a sample of breedCount in response to GAME_STARTED', () => {
const breedList = ['shiba', 'akita', 'kelpie', 'african', 'afghan-hound']

const action = {
type: GAME_STARTED,
payload: breedList
}

const newState = questionReducer(undefined, action)

expect(newState.currentBreeds.length).toEqual(newState.breedCount)
});

it('should initialize with an empty schema', () => {

const initialState = questionReducer()
expect(initialState.imageUrl).toEqual(null)
expect(initialState.currentBreeds).toEqual(null)
expect(initialState.correctAnswer).toEqual(null)
expect(initialState.breedCount).toEqual(3)
})