Last active
February 13, 2025 20:25
-
-
Save sturmenta/08150f005d9ba5f46da2795d72fdc38f to your computer and use it in GitHub Desktop.
Render stars for calification (convert number into amount of stars of each type)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const convertAverageRatingIntoStarsStatusObject = ( | |
averageRating: number | |
) => { | |
const parseDecimalToStar = { | |
1: 0, | |
2: 0, | |
3: 0.5, | |
4: 0.5, | |
5: 0.5, | |
6: 0.5, | |
7: 0.5, | |
8: 1, | |
9: 1, | |
}; | |
const numberHasDecimalPlace = | |
averageRating - Math.floor(averageRating) !== 0; | |
const decimalPartOfNumber = String(averageRating).split('.')[1]; | |
const showHalfStar = numberHasDecimalPlace | |
? parseDecimalToStar[decimalPartOfNumber] === 0.5 | |
: false; | |
const numberHasDecimalPlaceButShowFullStar = | |
numberHasDecimalPlace && parseDecimalToStar[decimalPartOfNumber] === 1; | |
return { | |
filled: | |
Math.trunc(averageRating) + | |
(numberHasDecimalPlaceButShowFullStar ? 1 : 0), | |
half: showHalfStar ? 1 : 0, | |
empty: | |
5 - | |
Math.trunc(averageRating) + | |
(showHalfStar || numberHasDecimalPlaceButShowFullStar ? -1 : 0), | |
}; | |
}; | |
// example: | |
// input: 3.7 | |
// output: {filled: 3, half: 1, empty: 1} | |
// with this data you can render stars icons |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment