gab-social/app/javascript/gabsocial/utils/numbers.js

32 lines
868 B
JavaScript
Raw Normal View History

import React from 'react'
2020-02-08 06:12:01 +00:00
import { FormattedNumber } from 'react-intl'
2019-07-02 08:10:25 +01:00
2020-04-29 03:24:35 +01:00
export const shortNumberFormat = (number) => {
if (isNaN(number)) {
return <FormattedNumber value={0} />
}
2019-07-02 08:10:25 +01:00
if (number < 1000) {
2020-04-29 03:24:35 +01:00
try {
return (<FormattedNumber value={number} />).props.value
} catch (error) {
return <FormattedNumber value={0} />
2020-04-29 03:24:35 +01:00
}
2019-07-02 08:10:25 +01:00
}
const isMillions = number > 999999
const isThousands = number > 999 && !isMillions
const divisor = isMillions ? 1000000 : isThousands ? 1000 : 1
const suffix = isMillions ? 'm' : isThousands ? 'k' : ''
2020-02-08 06:12:01 +00:00
return (
<React.Fragment>
<FormattedNumber value={number / divisor} maximumFractionDigits={1} />{suffix}
</React.Fragment>
2020-02-08 06:12:01 +00:00
)
}
export const getRandomInt = (min, max) => {
min = Math.ceil(min)
max = Math.floor(max)
return Math.floor(Math.random() * (max - min + 1)) + min
}