A more Functional Code, or is it Procedural?
Objectives
We would like to :Notes
- We will start with the X code.
- If you want, grab https://mirkwood.cs.edinboro.edu/~bennett/class/cmsc3780/spring2026/notes/javascript/code/start/newton.html this with wget.
- Remove the stuff that writes to the output area, just to clean things up a bit.
- We can keep the div if we want for debugging later.
- Let's add a function
- reference
- Syntax:
function identifier ([param] [, param ...]]) { body } - Parameters are by value
- basic types are just copied
- Objects are just pointer copy (so pass by pointer)
- You can return a single value
- But that is not a problem we can return an array of things if we want multiple returns.
- As a C++ programmer this is problematic for me.
- Let's build a function ChangePicture
- It takes on parameters
- And it does the moves and such to make an X.
-
function ChangePicture() { ctx.beginPath() ctx.moveTo(0,0) ctx.lineTo(width,height) ctx.strokeStyle="Red" ctx.stroke() ctx.beginPath() ctx.strokeStyle="Blue" ctx.moveTo(0,height); ctx.lineTo(width,0) ctx.stroke() } - We will still have to call it so add
ChangePicture()after the function is declared.
- Lets change this as follows
- Declare a function that takes an inset value
inset- We can assume that 0 ≤ inset ≤ min(width/2, height/2)
- Start each of the line segments moved in by this amount
- Call the function X.
- Call X inside of ChangePicture.
- Declare a function that takes an inset value
- My final code is here.