KnowCheck: PureFunctions Vs. Impure Flashcards
Making API/fetch calls to backend with Redux
useAction creatorsto make async calls and dispatch actions on completion. Reducer should bepure sync function.
https://stackoverflow.com/questions/56502838/is-it-ok-to-make-a-rest-api-request-from-within-a-redux-reducer
What is a pure function?
If given the same input, it woukd produce the same output.
Has no side effects
What is a “dead giveaway” a function is impure?
A dead giveaway that a function is impure is if it makes sense to call it without using its return value. For pure functions, that’s a noop.
Why use pure functions?
Abides by KISS:
- simplest reusable building blocks of code in a program.
- independent of outside state
- Pure functions are also extremely independent — easy to move around, refactor, and reorganize in your code, making your programs more flexible and adaptable to future changes.
What is the priblem you run into with shared state?
Any sort of asynchronous operation or concurrency could cause similar race conditions. Race conditions happen if output is dependent on the sequence of uncontrollable events (such as network, device latency, user input, randomness, etc…). In fact, if you’re using shared state and that state is reliant on sequences which vary depending on indeterministic factors, for all intents and purposes, the output is impossible to predict, and that means it’s impossible to properly test or fully understand.
Give an example of an impure function
Math.random()
Give an example of a oure function.
const double = (x) => { return 2*x }