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.
CodePudding user response:
You could just not iterate at all to be even faster and better to read:
const ratings = (rating, total) => ' ★ '.repeat(rating) ' ☆ '.repeat(total-rating);
document.write(ratings(3, 5));
CodePudding user response:
Or something like that...
const ratings = (rating, length) =>
Array.from({length},(_,i) => (i < rating) ? '★' : '☆')
.join(' ');
document.write(ratings(3, 5 ));
CodePudding user response:
You can use the methode Array.from
to create / initialize your first array.
Then you can map through this array to create your rating.
Don't forget to join
the result to get a string as a result.
const ratings = (rating, total) => Array.from({length: total})
.map((star, i) => (i < rating) ? ' ★ ' : ' ☆ ')
.join('');
document.write(ratings(3, 5 ));
CodePudding user response:
Your question is not about arrow functions per say, as you already have one, but rather how to think in terms of arrays and their methods.
First we create an array of total
length (1), as that will always be the numbers of stars irrespective of the type. This is a sparse array, so we need to .fill("whatever")
it to become something we can map
.
Then, each item is mapped to a corresponding star depending on whether its index is less than or equal to rating (2)
Notice the _
to ignore the actual item as we only care about the index.
This gives us the desired array of stars and all we have to do is join(" ")
them to have a proper string we can put in the document. (3)
const ratings = (rating, total) => {
return Array(total) // 1
.fill("")
.map((_, i) => i < rating ? "★" : "☆") // 2
.join(" ") // 3
};
document.write(ratings(3, 5 ));