Files

45 lines
846 B
JavaScript
Raw Permalink Normal View History

2022-11-08 20:21:29 +08:00
const fib = n => {
if (n == 0) {
2022-11-08 20:21:29 +08:00
return 0
}
if (n == 1) {
2022-11-08 20:21:29 +08:00
return 1
}
return fib(n - 1) + fib(n - 2)
}
2022-10-26 13:11:51 +08:00
/* external */
import { h, render } from "preact"
2022-10-26 13:11:51 +08:00
/* external */
import { Stateful } from "./stateful.js"
2022-10-26 13:11:51 +08:00
2022-11-08 21:09:42 +08:00
const Fibonacci = Stateful({
getInitialState: () => ({ index: 0 }),
2022-10-26 13:11:51 +08:00
handlers: {
prev: ({ index }, event) => ({ index: index - 1 }),
next: ({ index }, event) => ({ index: index + 1 }),
2022-10-26 13:11:51 +08:00
},
render: (props, state, handlers) =>
h(
"div",
null,
h(
"h1",
null,
"nth Fibonacci number is ",
2022-11-08 20:21:29 +08:00
fib(state.index),
" for n = ",
state.index,
2022-11-08 20:21:29 +08:00
),
h("button", { onClick: handlers.prev }, "Previous"),
" ",
h("button", { onClick: handlers.next }, "Next"),
" ",
),
2022-10-26 13:11:51 +08:00
})
2022-11-08 21:09:42 +08:00
render(h(Fibonacci), globalThis.document.body)