Redux with State

Modifying particles with Redux and using StateValue to detect data mutations

by IPWright83

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.7.2/redux.js"></script>
<svg width="960" height="500"></svg>

JavaScript

const nodes = 200;
const width = 960;
const height = 500;

const StateValue = function(v) {
     this._value = v;
     this._oldValue = v;
  
  	 this.setValue = (value) => {
     		this._oldValue = this._value;
     		this._value = value;
  	}
  
  	this.getValue = () => { return this._value; }
  	this.getHasMutated = () => { return this._value !== this._oldValue; }
}

const StateObj = function(row) {
	  this.xloc = new StateValue(row.xloc);
    this.yloc = new StateValue(row.yloc);
    this.xvel = new StateValue(row.xvel);
    this.yvel = new StateValue(row.yvel);
    
    this.setFromState = (row) => {
       this.xloc.setValue(row.xloc);
       this.yloc.setValue(row.yloc);
       this.xvel.setValue(row.xvel);
       this.yvel.setValue(row.yvel);
    }
    
    this.getHasMutated = () => { 
    	return this.xloc.getHasMutated() ||
             this.yloc.getHasMutated() || 
             this.xvel.getHasMutated() ||
             this.yvel.getHasMutated();
    };
}

const initState = {};
d3.range(nodes).forEach((d, i) => initState[i] = { xloc: 0, yloc: 0, xvel: 0, yvel: 0 });
const data = Object.values(initState).map(d => new StateObj(d));

const x = d3.scaleLinear().domain([-5, 5]).range([0, width]);
const y = d3.scaleLinear().domain([-5, 5]).range([0, height]);
let fps = d3.select("#fps span");
let time0 = Date.now();
let time1;

const circle = d3.select("svg")
								 .selectAll("circle")
                 .data(Object.values(initState)).enter()
                 .append("circle")
                 .attr("cx", 10)
                 .attr("cy", 10)
                 .attr("r", 1);
                 
const reducer = (state = initState, action) => {
	switch(action.type) {
  	case "VELOCITY": {
      const payload = action.payload;
    	const index = payload.i;
      const datum = state[index];
      const newDatum = { 
      	xloc: datum.xloc + datum.xvel,
        yloc: datum.yloc + datum.yvel,
        xvel: datum.xvel + payload.vx,
        yvel: datum.yvel +...