Created
November 18, 2017 02:24
-
-
Save row1/6d1dd916b349cee449a9952d319139b5 to your computer and use it in GitHub Desktop.
A contrived example showing the difference between pure and impure functions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ImpureCalc { | |
constructor() { | |
this.currentTotal = 0; | |
} | |
addToTotal(valueToAdd) { | |
this.currentTotal += valueToAdd; | |
return this.currentTotal; | |
} | |
} | |
class PureCalc { | |
addToTotal(currentTotal, valueToAdd) { | |
return currentTotal + valueToAdd; | |
} | |
} | |
const pureCalc = new PureCalc(); | |
const impureCalc = new ImpureCalc(); | |
console.log(`Impure call 1: ${impureCalc.addToTotal(5)}`); | |
console.log(`Impure call 2: ${impureCalc.addToTotal(5)}`); | |
console.log(`Pure call 1: ${pureCalc.addToTotal(0, 5)}`); | |
console.log(`Pure call 2: ${pureCalc.addToTotal(0, 5)}`); | |
// Prints: | |
// Impure call 1: 5 | |
// Impure call 2: 10 | |
// Pure call 1: 5 | |
// Pure call 2: 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment