I’m new to JavaScript
. Now I’m trying to write code that displays hearts based on numbers. Everything came out looking good. But there are some that are displayed incorrectly, namely the number 500. It is displayed as ๐๐งก But 600 it is displayed as ๐ And it happened to 5000 and 6000 too, I can’t find a solution right now.
The Code:
function numbertoheart(r) {
if (r <= 0) return "";
for (var o = "", f = 0; f < Math.floor(r / 100000); f++) o += "๐";
for (var $ = r % 100000, f = 0; f < Math.floor($ / 50000); f++) o += "๐";
for (var $ = r % 50000, f = 0; f < Math.floor($ / 10000); f++) o += "๐";
for (var $ = r % 10000, f = 0; f < Math.floor($ / 5000); f++) o += "๐";
for (var $ = r % 5000, f = 0; f < Math.floor($ / 2000); f++) o += "โฃ";
for (var $ = r % 2000, f = 0; f < Math.floor($ / 1000); f++) o += "๐";
for (var $ = r % 1000, f = 0; f < Math.floor($ / 500); f++) o += "๐";
for (var $ = r % 500, f = 0; f < Math.floor($ / 200); f++) o += "๐";
for (var $ = r % 200, f = 0; f < Math.floor($ / 100); f++) o += "๐งก";
for (var $ = r % 100, f = 0; f < Math.floor($ / 50); f++) o += "๐";
for (var $ = r % 50, f = 0; f < Math.floor($ / 10); f++) o += "๐";
for (var $ = r % 10, f = 0; f < Math.floor($ / 5); f++) o += "๐";
for (var $ = r % 5, f = 0; f < $; f++) o += "โค";
return o
}
console.log(numbertoheart(500));
console.log(numbertoheart(600));
console.log(numbertoheart(5000));
console.log(numbertoheart(6000));
Thank you in advance.
I want it to display correctly. It is similar to the rank system based on the number of points.
2
Answers
The issue with your code is that it processes the input number in multiple cases when it matches multiple conditions. To fix this, you should subtract the hearts added in each case from the original number to make sure it’s only processed once.
Fixed Code:
The problem is that after you add some hearts to the result, you don’t subtract their values from
r
.For instance,
r % 1000
is500
, so you display one ๐. Butr % 200
is100
, so you also display ๐งก.You should reduce
r
to the remainder of the value of that emoji after that loop. You can achieve that in your code be reusingr
instead of using$
in each loop.