I have a JavaScript function that converts a numeric rating like 3/5
to a visual rating using star HTML entities:
★ ★ ★ ☆ ☆
Here is my function:
function ratings(rating, total)
{
var stars = '';
for(var i = 0; i < total; i++)
{
if(i < rating)
{
stars += ' ★ ';
}
else
{
stars += ' ☆ ';
}
}
return stars;
}
document.write(ratings(3, 5 ));
I want to convert this to an arrow function. Here is what I have so far:
const ratings = (rating, total) => {
let stars;
for(var i = 0; i < total; i++)
{
if(i < rating)
{
stars += ' ★ ';
}
else
{
stars += ' ☆ ';
}
}
return stars;
};
document.write(ratings(3, 5 ));
I've seen some nice clean arrow function examples using map
, forEach
, and filter
to loop through an array. Is there anything similar that would work with my function? Not looping through an array, but looping x number of times.
Or something like that...
const ratings = (rating, length) =>
Array.from({length},(_,i) => (i < rating) ? '★' : '☆')
.join(' ');
document.write(ratings(3, 5 ));