Skip to content

Instantly share code, notes, and snippets.

@sturmenta
Last active February 13, 2025 20:25
Show Gist options
  • Save sturmenta/08150f005d9ba5f46da2795d72fdc38f to your computer and use it in GitHub Desktop.
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)
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