November 2017
Intermediate to advanced
386 pages
9h 22m
English
If a function becomes impure because it needs to call some other function that is itself impure, a way around this problem is to inject the required function in the call. This technique actually provides more flexibility in your code and allows for easier future changes, as well as less complex unit testing.
Let's consider the random filename generator function that we saw earlier. The problematic part is its usage of getRandomLetter() to produce the filename:
const getRandomFileName = (fileExtension = "") => { ... for (let i = 0; i < NAME_LENGTH; i++) { namePart[i] = getRandomLetter(); } ...};
A way to solve this is replacing the impure function, with an injected external one:
const getRandomFileName2 = (fileExtension ...
Read now
Unlock full access