index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // import parseTime, formatTime and set to filter
  2. export { parseTime } from '@/utils'
  3. import { formatDate } from '@/utils'
  4. /**
  5. * Show plural label if time is plural number
  6. * @param {number} time
  7. * @param {string} label
  8. * @return {string}
  9. */
  10. function pluralize(time, label) {
  11. if (time === 1) {
  12. return time + label
  13. }
  14. return time + label + 's'
  15. }
  16. /**
  17. * @param {number} time
  18. */
  19. export function timeAgo(time) {
  20. const between = Date.now() / 1000 - Number(time)
  21. if (between < 3600) {
  22. return pluralize(~~(between / 60), ' minute')
  23. } else if (between < 86400) {
  24. return pluralize(~~(between / 3600), ' hour')
  25. } else {
  26. return pluralize(~~(between / 86400), ' day')
  27. }
  28. }
  29. /**
  30. * Number formatting
  31. * like 10000 => 10k
  32. * @param {number} num
  33. * @param {number} digits
  34. */
  35. export function numberFormatter(num, digits) {
  36. const si = [
  37. { value: 1e18, symbol: 'E' },
  38. { value: 1e15, symbol: 'P' },
  39. { value: 1e12, symbol: 'T' },
  40. { value: 1e9, symbol: 'G' },
  41. { value: 1e6, symbol: 'M' },
  42. { value: 1e3, symbol: 'k' }
  43. ]
  44. for (let i = 0; i < si.length; i++) {
  45. if (num >= si[i].value) {
  46. return (num / si[i].value).toFixed(digits).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, '$1') + si[i].symbol
  47. }
  48. }
  49. return num.toString()
  50. }
  51. /**
  52. * 10000 => "10,000"
  53. * @param {number} num
  54. */
  55. export function toThousandFilter(num) {
  56. return (+num || 0).toString().replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
  57. }
  58. /**
  59. * Upper case first char
  60. * @param {String} string
  61. */
  62. export function uppercaseFirst(string) {
  63. return string.charAt(0).toUpperCase() + string.slice(1)
  64. }
  65. export function formatTime(time) {
  66. if (!time) {
  67. return ''
  68. }
  69. return formatDate(time, 'yyyy-MM-DD HH:mm:ss')
  70. }
  71. export function formatPrice(price) {
  72. if (!price) {
  73. return 0
  74. }
  75. return parseInt(price).toFixed(2)
  76. }