I have been working on this Lorenz Attractor visualization for the past day. I am currently also trying to change my coding style into a more functional programming one.
I find it quite hard, to be honest, especially the "Only use pure functions." rule. That mostly means no side effects and functions that perform 1 small task. The "No side effect." rule is, of course, impossible while drawing on the HTML canvas. So I am looking for performance optimization and code style tips for FP in general.
I also should like to pass the 3 global variables (x, y, z) as parameters when calling the update function ("No global variables allowed.") however I have had no luck so far. I can't find a way to keep them from resetting while using parameters. Unlike the draw function that calls itself. Any help is welcome, thanks for your time.
https://jsfiddle.net/9r8qcgnh/3/
{
const canvas = document.querySelector('#canvas')
const ctx = canvas.getContext('2d')
ctx.fillStyle = 'rgb(255, 255, 255)'
ctx.translate(500, 400)
ctx.scale(10.5, 10.5)
let x = 0.01
let y = 0.0
let z = 0.0
function update () {
const a = 10.0
const b = 28.0
const c = 8.0 / 3.0
const dt = 0.015
const dx = a * (y - x) * dt
const dy = (x * (b - z) - y) * dt
const dz = (x * y - c * z) * dt
x = x + dx
y = y + dy
z = z + dz
return { x: x, y: y, z: z }
}
function draw (hue) {
const { x, y } = update()
hue = hue || 0
hue >= 240 ? (hue = 0) : hue++
ctx.fillStyle = `hsl(${hue},100%, 50%)`
ctx.fillRect(x, y, 0.1, 0.1)
setTimeout(() => {
return draw(hue)
}, 5)
}
draw()
}