Skip to content

Commit 676ddf2

Browse files
committed
Refactoring makes me feel alive
1 parent aa7d5ce commit 676ddf2

File tree

2 files changed

+18
-16
lines changed

2 files changed

+18
-16
lines changed

src/App.tsx

+6-4
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,12 @@ const Factorial: FC<any> = React.memo(({ n }) => {
1313
Calculating factorial of {n}...
1414
<IfElse condition={count <= 1}>
1515
<Add>{result}</Add>
16-
<CallElement key={count} fn={<EvaluateAll fns={[
17-
<Add><Decrement>{numberToNode(count)}</Decrement></Add>,
18-
<Multiply a={result} b={numberToNode(count)} />
19-
]} />}>
16+
<CallElement key={count} fn={
17+
<EvaluateAll fns={[
18+
<Add><Decrement>{numberToNode(count)}</Decrement></Add>,
19+
<Multiply a={result} b={numberToNode(count)} />
20+
]} />
21+
}>
2022
{([newCount, newResult]) => <CallFunction fn={() => {
2123
setCount(newCount);
2224
setResult(numberToNode(newResult))

src/program/compute.tsx

+12-12
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,20 @@ declare module 'react' {
55
export function use<T>(x: Promise<T>): T | undefined;
66
}
77

8+
export const useLoop = () => {
9+
const [state, update] = useReducer((s) => !s, false);
10+
11+
useEffect(() => {
12+
if ((window as any).PLEASE_STOP) return; // Emergency stop looping
13+
setTimeout(() => flushSync(() => update()), 50);
14+
}, [state]);
15+
}
16+
817
export const PickChild: FC<{ n: number; children: ReactNode }> = ({ n, children }) =>
918
Children.toArray(children)[n];
1019

1120
export const IfElse: FC<{ condition: boolean; children: [ReactNode, ReactNode] }> = ({ condition, children }) =>
12-
<PickChild n={+!condition}>{children}</PickChild>;
21+
<PickChild n={Number(!condition)}>{children}</PickChild>;
1322

1423
export const CallFunction: FC<{ fn: () => void }> = ({ fn }) => {
1524
const fnRef = useRef(fn);
@@ -50,12 +59,11 @@ export const CallElement: FC<{
5059
export const EvaluateAll: FC<{ fns: ReactNode[] }> = ({ fns }) => {
5160
const onReturn = useContext(Return);
5261
const resultList = useRef<any[]>([]);
53-
const resultCount = useRef(0);
5462

5563
const resolve = useCallback((result: any, i: number) => {
5664
resultList.current[i] = result;
57-
resultCount.current++;
58-
if (resultCount.current === fns.length) {
65+
const resultCount = resultList.current.filter(_ => true).length;
66+
if (resultCount === fns.length) {
5967
onReturn(resultList.current);
6068
}
6169
}, [fns.length, onReturn])
@@ -71,11 +79,3 @@ export const EvaluateAll: FC<{ fns: ReactNode[] }> = ({ fns }) => {
7179
)
7280
}
7381

74-
export const useLoop = () => {
75-
const [state, update] = useReducer((s) => !s, false);
76-
77-
useEffect(() => {
78-
if ((window as any).PLEASE_STOP) return;
79-
setTimeout(() => flushSync(() => update()), 50);
80-
}, [state]);
81-
}

0 commit comments

Comments
 (0)