Skip to content

Instantly share code, notes, and snippets.

@row1
Created November 18, 2017 02:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save row1/6d1dd916b349cee449a9952d319139b5 to your computer and use it in GitHub Desktop.
Save row1/6d1dd916b349cee449a9952d319139b5 to your computer and use it in GitHub Desktop.
A contrived example showing the difference between pure and impure functions.
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