/* In this trivial example we want 'a' to equal 50 and we want 'b' to equal 100. */constoptimized=optimize({iterations: 10000,initialState: ()=>{conststate={a: 10,b: 20};returnstate;},mutateState: (state)=>{constmutantState=Object.assign({},state);mutantState.a+=(Math.random()*2)-1;mutantState.b+=(Math.random()*2)-1;returnmutantState;},fitness: (state)=>{constaTarget=50;constbTarget=100;letfitness=0;fitness+=Math.abs(state.a-aTarget);fitness+=Math.abs(state.b-bTarget);returnfitness;}});constoptimizedState=optimized.state;// { a: 50.00927231281881, b: 100.00184294400155 }constoptimizedFitness=optimized.fitness;// 0.011115256820360742
Caveats
Optimization will only be as performant as the quality of the fitness function, and mutateState function provided to it.
If you perform mutateState in an immutable way (either manually or with a library like immutable.js) all internal operations of the library will be immutable. In the event no better state is found than the state object provided in initialState, the state object itself provided in initialState is returned.
The internal process to optimize is a simple hill climbing algorithm (ie. mutate and replace is better), there is no artificial genetics or other algorithms taking place.