Skip to content

Commit

Permalink
Merge pull request #244 from Chia-Network/quiz
Browse files Browse the repository at this point in the history
Improve runnable code blocks
  • Loading branch information
mando222 authored Oct 2, 2023
2 parents d1fdb89 + bf5a448 commit 1716e12
Show file tree
Hide file tree
Showing 3 changed files with 290 additions and 184 deletions.
38 changes: 38 additions & 0 deletions src/components/Quiz.tsx
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}%`}
</>
);
}
Loading

0 comments on commit 1716e12

Please sign in to comment.