Search code examples
javascriptloopsarrow-functions

JavaScript Arrow Functions and a For Loop


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 += ' &starf; ';
        }
        else 
        {
            stars += ' &star; ';
        }   
    }
    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 += ' &starf; ';
        }
        else 
        {
            stars += ' &star; ';
        }   
    }
    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.


Solution

  • Or something like that...

    const ratings = (rating, length) =>
       Array.from({length},(_,i) => (i < rating) ? '&starf;' : '&star;')
       .join(' ');
       
    document.write(ratings(3, 5 ));