In Redux Tutorial, they have used array spread operator a lot for writing reducers(which have to be pure functions) . Go through the following script.
let a = {
b : "ddff",
c : "adxas"
}
let c = {
b : "ssdds",
c : "asdxasdsad"
}
let d = [];
d.push(a);
d.push(c);
console.log(d);
const pureFunc = (arr,b,c) => {
return [...arr, { b , c}];
}
let n = pureFunc(d,"daaaa","sdadad");
console.log(n);
d[0].b = "Hello";
console.log(n)
Is the function "pureFunc" is a proper pure function. Mutations on array d are getting reflected in object n.
Yes, pureFunc
is pure. The mutation does not occur within pureFunc
.
One of the most common and basic pure functions is the identity function:
let identity = x => x;
So, if we pass that an object, we'll get the same object back. We can modify it after the fact, but that doesn't make identity
impure, because identity
isn't doing the mutation.
Basically, pure functions only need to satisfy two requirements: