Skip to content

Instantly share code, notes, and snippets.

@dengjonathan
Created November 21, 2016 20:01
Show Gist options
  • Save dengjonathan/7ad472984f4db4b52b0e3e35c911776a to your computer and use it in GitHub Desktop.
Save dengjonathan/7ad472984f4db4b52b0e3e35c911776a to your computer and use it in GitHub Desktop.
pure examples 1
// 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!
@szkrd
Copy link

szkrd commented Nov 23, 2016

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment