Pure functions when working with DOM manipulation

Viewed 1560

I am trying to wrap my head around pure functions, but I am not sure that I really understand it. I know that pure functions shouldn't mutate external state, and it should return the same output every time as long as it has the same input.

I know that for example this function is impure, because it mutates the cart variable which other parts of the program may use:

const addToCart = (cart, item) => { 
  cart.push(item); 
  return cart; 
};

The same function in a pure state:

const addToCart = (cart, item) => { 
  const newCart = lodash.cloneDeep(cart); 
  newCart.push(item); 
  return newCart; 
};

This makes sense to me. I have learned that pure functions should always return something.

However, I am working on some stuff that requires me to use the HTML5 canvas element, and I have this function which clears the canvas:

function clearCanvas(canvas) { 
  canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height); 
}

How can I make the above function pure? I realize it's impure because it doesn't return anything, also it mutates the state of the canvas variable. Is DOM-manipulation inherently impure?

Any help would be appreciated :)

3 Answers
Related