Reputation: 1379
Let's consider a functional component that has a mutable internal state:
const FComponent = (options: any) => {
let privateID = '0000';
return {
...{ // Public fields
name: 'component'
},
...{ // Public methods
setPrivateID: (id: string) => {
privateID = id;
}
}
}
};
FComponent({}).setPrivateID('0001');
Should I rather return a new component that has the requested ID ?
Something like this ? A Functor I suppose ? https://medium.com/javascript-scene/functors-categories-61e031bac53f
const FComponent = (options: {id: string}) => {
return {
...{
name: 'component'
},
...{
privateID: (id: string) => {
return FComponent({id})
}
}
}
};
Upvotes: 0
Views: 66
Reputation: 48745
A function that mutates state isn't pure since mutating state is a side effect.
The second version does not mutate state but creates a new object. This is how the String class in Java works, which is purely functional.
Upvotes: 1