How to iterate over a callback n times in JavaScript ?
Last Updated :
30 Dec, 2022
Given a callback function, we have to iterate over a callback n times. The callback is a function that is passed as an argument. To iterate over the callback function, we have to run the callback function n time.
Approach 1: We use recursion to iterate the n times callback function.
- First, create a callback function factor that takes n as an argument.
- The factor function generates a pattern of n length.
- Create a test function that takes a callback function and n.
- The test function checks the value of n is equal to 0 and not.
- If n is 0 it returns the terminate test function, else it calls the callback function which prints the pattern.
Example: This example uses the above approach.
Javascript
<script>
function factor(n) {
if (n <= 1) {
console.log( "0" + n);
return ;
}
let str = "" ;
for (let i = 1; i <= n; i++) {
str += `0${i} `;
}
console.log(str);
return factor(n - 1);
}
function test(n, callback) {
if (n == 0) {
console.log( "please provide value n greater than 0" );
return ;
}
let k = n;
callback(k);
}
let t_number = 4;
test(t_number, factor);
</script>
|
Output:
01 02 03 04
01 02 03
01 02
01
Approach 2: We use a loop statement to iterate over the callback.
- First, we create a callback function factor which generates a factorial of numbers.
- Create a test function with argument n and a callback function.
- Check the value of n if it is invalid terminate if not continue.
- Create for loop with range n.
- On each loop call the callback function which prints the factorial of each number.
Example: This example describes the above explained approach.
Javascript
<script>
function factor(number) {
let j = 1;
for (let i = 1; i <= number; i++) {
j *= i;
}
console.log(`factorial of ${number} is `);
console.log(j);
}
function test(n, callback) {
if (n <= 0) {
console.log( "invalid number" );
return ;
}
let k = n;
for (let i = k; i >= 1; i--) callback(i);
}
let t_umber = 5;
test(t_umber, factor);
</script>
|
Output:
factorial of 5 is 120
factorial of 4 is 24
factorial of 3 is 6
factorial of 2 is 2
factorial of 1 is 1
Share your thoughts in the comments
Please Login to comment...