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 are there any recommendations on what design patterns 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 does one abstract the logic in the if
-statement to begin with?
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...");
}
};
}
Array
of buckets and just looping through until you find two you can transfer between? \$\endgroup\$