I have been trying to create a function that would result in a repeated set of numbers if used in a for loop. If I’m using numbers 1–5, I should see a pattern of 1, 2, 3, 4, 5, 1, 2, 3, 4, 5 in the console.
To do this, I start by finding the remainder of dividing the current interval by the greatest number in the set (5). For example:
1 % 5 gives me 1,
2 % 5 = 2,
3 % 5 = 3,
4 % 5 = 4,
5 % 5 = 0,
and 6 % 5 should give me 1 again.
Here is the function I used:
function patternItem(x, lastNum) {
return (x % lastNum);
}
console.clear();
for (var i = 1; i <= 10; ++i) {
console.log(patternItem(i, 5));
}
I am trying to do this without having to force 5 for every remainder of 0. In other words, I want to avoid writing the function like this or similar:
function patternItem(x, lastNum) {
let rem = x % lastNum;
return rem != 0 ? rem : lastNum;
}
So far, I haven’t had any luck. What sort of complex formula would I need for the function?
With slight variation in your code
i to 0 and condition to < instead of <=.return x % lastNum + 1 for returning 1 while reminder is 0.function patternItem(x, lastNum) {
return x % lastNum + 1;
}
console.clear();
for (var i = 0; i < 10; ++i) {
console.log(patternItem(i, 5));
}
Just start at 0 and add 1:
function patternItem(x, lastNum) {
return x % lastNum;
}
for (var i = 0; i < 10; ++i) {
console.log(patternItem(i, 5) + 1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With