# Finding closed loops in a number - JavaScript

Javascript LibraryWeb DevelopmentFront End TechnologyObject Oriented Programming

Other than all being a natural number, the numbers 0, 4, 6, 8, 9 have one more thing in common. All these numbers are formed by or contain at least one closed loop in their shapes.

For example, the number 0 is a closed loop, 8 contains two closed loops and 4, 6, 9 each contains one closed loop.

We are required to write a JavaScript function that takes in a number and returns the sum of the closed loops in all its digits.

For example, if the number is 4789

Then the output should be 4 i.e.

1 + 0 + 2 + 1

## Example

Following is the code −

const num = 4789;
const calculateClosedLoop = (num, {
count,
legend
} = {count: 0, legend: {'0': 1, '4': 1, '6': 1, '8': 2, '9': 1}}) => {
if(num){
return calculateClosedLoop(Math.floor(num / 10), {
count: count + (legend[num % 10] || 0),
legend
});
};
return count;
};
console.log(calculateClosedLoop(num));

## Output

Following is the output in the console −

4
Published on 18-Sep-2020 09:00:51