0

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})
               }
          }
     }
};

millsp
  • 1,259
  • 1
  • 10
  • 23
  • 1
    See https://stackoverflow.com/questions/31722181/can-an-immutable-type-change-its-internal-state... if the internal state is unobservable from the outside then you can mutate it and still consider the function "pure". From your code above it doesn't look like anyone could retrieve the private id. – jcalz Jan 13 '19 at 00:40

1 Answers1

1

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.

Sylwester
  • 47,942
  • 4
  • 47
  • 79