refactor: drastically simplified reducers

This commit is contained in:
cha0s 2019-03-27 02:05:08 -05:00
parent 5f53f6e87f
commit 1ebcb177bf

View File

@ -28,49 +28,34 @@ class InformedBase extends Trait {
}
}
reduceStateDiffForEntityList(diff, position) {
// Only if entity list exists.
if (!diff.entityList) {
return diff;
}
// Reduce the entity list.
const informSize = this.entity.informSize.toJS();
const nearbyEntities = this.entity.nearbyEntities(informSize, position);
const reducedEntityList = {};
let nearby = I.Set();
for (const entity of nearbyEntities) {
nearby = nearby.add(entity);
const uuid = entity.instanceUuid;
if (this.lastNearby.has(entity)) {
// Keep diff.
if (diff.entityList[uuid]) {
reducedEntityList[uuid] = diff.entityList[uuid];
createIndexedReducer() {
let previous = {};
return (diff, indexed) => {
const reducedDiff = {};
const current = {};
for (const index in indexed) {
const item = indexed[index];
current[index] = item;
// Diff.
if (previous[index]) {
if (diff[index]) {
reducedDiff[index] = diff[index];
}
}
// Added.
else {
reducedDiff[index] = item.state.toJS();
}
}
else {
// Added.
reducedEntityList[uuid] = entity.state().toJS();
// Removed.
for (const index in previous) {
if (!current[index]) {
reducedDiff[index] = false;
}
}
}
for (const entity of this.lastNearby.values()) {
const uuid = entity.instanceUuid;
if (!nearby.has(entity)) {
// Removed.
reducedEntityList[uuid] = false;
}
}
// Track who's nearby.
this.lastNearby = nearby;
// Merge the reduction.
diff = {
...diff,
entityList: reducedEntityList,
previous = current;
return reducedDiff;
};
// Remove dead update.
if (0 === Object.keys(diff.entityList).length) {
delete diff.entityList;
}
return diff;
}
get socket() {
@ -83,6 +68,8 @@ class InformedBase extends Trait {
}
methods() {
const entityReducer = this.createIndexedReducer();
const layerReducer = this.createIndexedReducer();
return {
inform: (diff) => {
@ -100,8 +87,38 @@ class InformedBase extends Trait {
});
},
reduceStateDiff: (diff, position) => {
return this.reduceStateDiffForEntityList(diff, position);
reduceStateDiff: (diff) => {
diff.room = diff.room || {};
diff.room.layers = diff.room.layers || {};
// Index layers.
const room = this.entity.room;
const indexedLayers = {};
for (const index in room.layers.layers) {
const layer = room.layers.layers[index];
indexedLayers[index] = layer;
}
// Reduce layers.
diff.room.layers = layerReducer(
diff.room.layers,
indexedLayers,
);
for (const index in diff.room.layers) {
// Index entities.
const layer = room.layers.layers[index];
const visibleEntities = layer.entityList.visibleEntities(
[0, 0, 640, 360]
);
const indexedEntities = {};
for (const entity of visibleEntities) {
indexedEntities[entity.instanceUuid] = entity;
}
// Reduce entities.
diff.room.layers[index].entityList = entityReducer(
diff.room.layers[index].entityList,
indexedEntities,
);
}
return diff;
},
};