A pure function is a function that, given the same input, will always return the same output and does not have any observable side effect.
slice
and splice
. They are two functions that do the exact same thing - in a vastly different way, mind you, but the same thing nonetheless. We say slice
is pure because it returns the same output per input every time, guaranteed. splice
, however, will chew up its array and spit it back out forever changed which is an observable effect.splice
that mutate data. This will never do as we're striving for reliable functions that return the same result every time, not functions that leave a mess in their wake like splice
.checkAge
depends on the mutable variable minimum
to determine the result. In other words, it depends on system state which is disappointing because it increases the cognitive load by introducing an external environment.checkAge
may return different results depending on factors external to input, which not only disqualifies it from being pure, but also puts our minds through the wringer each time we're reasoning about the software.minimum
immutable, which preserves the purity as the state will never change. To do this, we must create an object to freeze.A side effect is a change of system state or observable interaction with the outside world that occurs during the calculation of a result.
A function is a special relationship between values: Each of its input values gives back exactly one output value.
x
to y
;5
points to several outputs:[(1,2), (3,6), (5,10)]
(It appears this function doubles its input).x
as the input and y
as the output:[]
instead of ()
.arguments
object as the input. When we learn about currying, we'll see how we can directly model the mathematical definition of a function.)url
and params
.memoize
function works just fine, though it doesn't cache the results of the http call, rather it caches the generated function.Db
, Email
, and attrs
which should be telling to say the least.Db
and Email
we have at the time.decrementHP
, isSameTeam
and punch
are all pure and therefore referentially transparent. We can use a technique called equational reasoning wherein one substitutes "equals for equals" to reason about code. It's a bit like manually evaluating the code without taking into account the quirks of programmatic evaluation. Using referential transparency, let's play with this code a bit.isSameTeam
.decrementHP
, we see that, in this case, punch becomes a call to decrement the hp
by 1.