Pure functions when working with DOM manipulations

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

I know that, for example, this function is unclean because it mutates a basket variable that other parts of the program can use:

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

The same functions in their pure form:

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

That makes sense to me. I found out that pure functions should always return something.

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

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

? , , , . DOM- ?

:)

+4
3

DOM- . "" .

, , , , .

DOM- ; - ( ), .


, , , , / .

, , , , , , .

+1

IO

IO - IO thunk , runIO. , IO map , .

- . 9:


// IO :: (void -> a) -> IO a
const IO = f => ({
  // runIO :: void -> a
  runIO: f,
  // map :: IO a => (a -> b) -> IO b
  map: g =>
    IO(() => g(f())),
  // chain :: IO a => (a -> IO b) -> IO b
  chain: g =>
    IO(g(f()).runIO)
})

// IO.of :: a -> IO a
IO.of = x => IO(() => x)

// log :: String -> a -> IO a
const log = label => x =>
  IO(() => (console.log(label, x), x))

// $ :: String -> IO HTMLElement
const $ = x =>
  IO(() => document.querySelector(x))

// getText :: HTMLElement -> String
const getText = e =>
  e.textContent

// main :: String -> IO String
const main = selector =>
  $(selector)
    .map(getText)
    .chain(log('A'))
    .map(s => s.toUpperCase())
    .chain(log('B'))
    .runIO()

main('title')
// A hello world
// B HELLO WORLD
<title>hello world</title>
Hide result
+2

function clearCanvas(canvas) { 
    const imgData = canvas.getContext('2d').getImageData(0,0,canvas.width,canvas.height);
    new Uint32Array(imgData.data.buffer).set(0);
    return data;
} 

canvas.getContext('2d').setImageData(clearCanvas(canvas),0,0);

, .

- , , . , .

0

Source: https://habr.com/ru/post/1677680/


All Articles