Reputation: 1571
I have a code that takes in a user input of an integer "X" and then repeats it Math.ceil(X/3)
amount of times, so I used this. Let "X" be 10 in this example
function repeat(func, times) {
func();
--times && repeat(func, times);
}
function test() {
console.log('test');
}
repeat(function() { test(); }, Math.ceil(10 / 3));
I would like to tweak this a bit so that the code would return the value of how much "X" was subtracted by until it reaches 0, but if the final value is negative it would return the "X" amount left itself. Sorry if that sounded confusing, Here's what I mean to further clarify what I'm aiming for:
/* The user inputs X as 10
I would like the ouput to look like this: */
"test 3" //10-3=7 so 7 left, return 3 to output
"test 3" //7-3=4 so 4 left, return 3 to output
"test 3" //4-3=1 so 0 left, return 3 to output
"test 1" //1-3=-2 would be less than 0, so do 1-1 instead and that results to 0, return 1 to output and end loop
Upvotes: 1
Views: 346
Reputation: 68393
You need to pass the actual numbers to repeat
rather than just a result of 10/3
, since it will not know otherwise when to stop.
Demo
function repeat(func, num1, num2 )
{
num1 > num2 ? func(num2) : func(num1);
if ( num1 > num2 )
{
num1 -= num2;
repeat(func, num1, num2);
}
}
function test(times) {
console.log('test', times)
}
repeat(test, 10, 3);
Upvotes: 1