-
Notifications
You must be signed in to change notification settings - Fork 56
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #244 from Chia-Network/quiz
Improve runnable code blocks
- Loading branch information
Showing
3 changed files
with
290 additions
and
184 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import React, { ReactNode, useMemo, useReducer } from 'react'; | ||
|
||
export type CorrectReporter = React.Dispatch<React.SetStateAction<boolean>>; | ||
|
||
export interface QuizProps { | ||
content: (newReporter: () => CorrectReporter) => ReactNode; | ||
} | ||
|
||
export default function Quiz({ content }: QuizProps) { | ||
const [_, forceUpdate] = useReducer((x) => x + 1, 0); | ||
const states = useMemo<Array<boolean | null>>(() => [], [content]); | ||
const resolved = useMemo(() => { | ||
let i = 0; | ||
return content(() => { | ||
const pos = i++; | ||
if (pos >= states.length) states.push(null); | ||
return (value) => { | ||
const result = | ||
typeof value === 'boolean' ? value : value(states[pos] ?? false); | ||
states[pos] = result; | ||
forceUpdate(); | ||
}; | ||
}); | ||
}, [content]); | ||
|
||
const isComplete = states.findIndex((state) => state === null) === -1; | ||
const score = Math.floor( | ||
(states.filter((value) => value === true).length / states.length) * 100 | ||
); | ||
|
||
return ( | ||
<> | ||
{resolved} | ||
<br /> | ||
{!isComplete ? 'Incomplete' : `Score: ${score}%`} | ||
</> | ||
); | ||
} |
Oops, something went wrong.