A quick example of how to refactor out a While loop in JavaScript by using recursion instead. The problem is as follows (from TestDome):
Your company assigns each customer a membership ID, and you are implementing a check digit for those IDs.
The check digit should be calculated by adding up all digits in each membership ID. If the result of the sum is a number with more than a single digit, another iteration is required, and the digits of the result also should be added together. This process should repeat until a single-digit number is calculated.
For example, for the membership ID “55555” the sum of all digits is 25. Because this is not a single-digit number, 2 and 5 would be added, and the result, 7, would be the check digit.
One way to do this is using a while loop, which looks like this:
function createCheckDigit(membershipId) {
let arr = membershipId.split('');
while (arr.length > 1) {
arr = arr.reduce((count, item) => {
return count + parseInt(item);
},0);
arr = arr.toString().split('');
}
return arr[0];
}
console.log(createCheckDigit("55555"));
We can refactor out the while loop by using recursion as so:
function createCheckDigit(membershipId) {
let arr = membershipId.split('');
if (arr.length === 1) {
return arr[0];
}
arr = arr.reduce((count, item) => {
return count + parseInt(item);
}, 0);
return createCheckDigit(arr.toString());
}
console.log(createCheckDigit("55555"));
The thing to remember about recursion is the recursive call should be preceded by the return statement, if you want something back. Here we get back arr[0]. Otherwise, the function returns “undefined.”