Reputation: 4701
I wrote a function to calculate the modulus of a function but when I run it in the console it always returns undefined. If I use the console.log I can see that it is calculating the correct value.
function modulo(sum, divider){
function loop(difference){
if(difference < divider){
console.log(difference)
return difference
} else {
setTimeout(loop(difference - divider), 0)
}
}
return loop(sum - divider)
}
modulo(8, 5) // 3
what I want is this to return the answer e.g.
var result = modulo(8, 5) // 3
Update:
A better solution to this problem would be
modulo = function (x,y){ return x - y * Math.floor(x/y) }
Upvotes: 0
Views: 483
Reputation: 20928
To answer your original question, setTimeout
is asynchronous, and your loop
function returns undefined, hence you get undefined. To make it do what you want, call loop
directly, or use promises.
But on the other hand, even if you were to implement modulus, this is a poor approach. Use some better division algorithms instead.
Upvotes: 2
Reputation: 3090
Because your code does not return value from the loop.
Try this:
function modulo(sum, divider) {
function loop(difference) {
if (difference < divider) {
return difference;
} else {
return loop(difference - divider);
}
}
return loop(sum - divider);
}
alert(modulo(8, 5));
Upvotes: 0
Reputation: 128791
You don't need to create a new function for this, JavaScript already has it's own modulus operator: %
.
8 % 5
-> 3
If you really want to turn this into a function, you can simply:
function modulo(sum, divider) {
return sum % divider;
}
modulo(8, 5);
-> 3
Upvotes: 3