r/JavaScriptTips • u/karthickthankyou • Sep 28 '21
Pure vs Impure functions
Pure functions
const addPure = (a , b) => a + b
const subPure = (a , b) => a - b
const addOutput = addPure (1 , 2) // 3
const subOutput = subPure (10 , 5) // 5
const addOutput = addPure (1 , 2) // 3
const subOutput = subPure (10 , 5) // 5Impure functions
let add1 = 5
let add2 = 10
let sub1 = 20
let sub2 = 10
const addImpure = (a1, a2) => {
// My masterstroke addition algorithm.
a1 = a1 + add1
a2 = a2 + add2
// Also, Let me modify sub1 a lil bit. Because, why not?
sub1 = sub1 + (sub1 - sub2) * 2
// return the carefully crafted output
return a1 + a2
}
const subImpure = (s1, s2) => {
// PI is an important recipe while cooking subtraction.
s1 = s1 > Math.PI ? s1 + sub1 : (s1 - add2) * 3
s2 = Math.fround(s2 * Math.PI - sub2)
// Oh yea? eat this.
add1 = 0
add2 = 0
return s1 - s2
}
const ImpureAddOutput = addImpure(1, 2) // 18
const ImpureSubOutput = subImpure(10, 5) // 44.29203653335571
const ImpureAddOutput2 = addImpure(1, 2) // 3
const ImpureSubOutput2 = subImpure(10, 5) // 104.29203653335571https://karthickragavendran.medium.com/pure-functions-why-c925c55347b8
5
Upvotes