I have a set of if/else statements that trigger certain actions.
As a first step, I was thinking about moving the logic in each if statement to be its own function, but any recommendations on what design patterns that can help clean this code up?
I guess I am trying to see if there is a cleaner way to determine what the next action/command should be based on a set of criteria.
I see people recommend the Command pattern, but how do abstract the logic in the if-statement to begin with?
The code is shown here:
function WaterRetriever(largeBucketSize, smallBucketSize, waterSize) {
var buckets = {};
if (waterSize > largeBucketSize) {
throw new Error("The buckets are not large enough.");
}
buckets.firstContainer = new Bucket(largeBucketSize);
buckets.secondContainer = new Bucket(smallBucketSize);
this.getWaterFromLake = function () {
var maxSteps = 25,
step = 1;
buckets.firstContainer.fill();
while (step <= maxSteps && buckets.firstContainer.getCurrentAmount() !== waterSize) {
if (buckets.firstContainer.isFull() && buckets.secondContainer.isEmpty()) {
buckets.firstContainer.transferTo(buckets.secondContainer);
} else if (buckets.secondContainer.isFull() && buckets.firstContainer.hasCapacityAvailable()) {
buckets.secondContainer.empty();
buckets.firstContainer.transferTo(buckets.secondContainer);
} else if (buckets.firstContainer.isEmpty() && buckets.secondContainer.hasCapacityAvailable()) {
buckets.firstContainer.fill();
} else if (buckets.firstContainer.isFull() && buckets.secondContainer.hasCapacityAvailable()) {
buckets.firstContainer.transferTo(buckets.secondContainer);
}
console.log(buckets.firstContainer.getCurrentAmount() + ", " + buckets.secondContainer.getCurrentAmount());
step = step + 1;
}
if (step > maxSteps) {
console.log("could not find a solution within the steps limit...");
}
};
}