Created
November 21, 2016 20:01
-
-
Save dengjonathan/7ad472984f4db4b52b0e3e35c911776a to your computer and use it in GitHub Desktop.
pure examples 1
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
// pure | |
const addOne = num => num + 1; | |
//impure: modifies input variable | |
const addOneImpure = num => num++; | |
//pure | |
const addOneToAll = arr => arr.map(addOne); | |
//impure: modifies input array | |
const addOneToAllImpure = arr => { | |
for (let i = 0; i < arr.length; i++) { | |
addOneImpure(arr[i]); | |
} | |
} | |
//pure | |
const addWheels = (obj, num) => Object.assign({}, obj, {wheels: num}); | |
const noWheelTruck = {type: 'truck'}; | |
const fourWheelTruck = addWheels(noWheelTruck, 4) //=> {type: 'truck', wheels: 4} | |
console.log(noWheelTruck) // {type: 'truck'} original object unchanged | |
//impure | |
const addWheelsImpure = (obj, num) => {obj['wheels'] = num}; | |
const noWheelCar = {type: 'car'}; | |
const fourWheelCar = addWheelsImpure(noWheelCar, 4); //=>{type: 'car', wheels: 4} | |
console.log(noWheelCar) //{ type: 'car', wheels: 4 } MUTATED! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think
addOneImpure
will not do anything, it should be++num
, but even if you did that, the number is a primitive thus it will not modify the passed variable.