util.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. function formatTime(time) {
  2. if (typeof time !== 'number' || time < 0) {
  3. return time
  4. }
  5. const hour = parseInt(time / 3600, 10)
  6. time %= 3600
  7. const minute = parseInt(time / 60, 10)
  8. time = parseInt(time % 60, 10)
  9. const second = time
  10. return ([hour, minute, second]).map(function (n) {
  11. n = n.toString()
  12. return n[1] ? n : '0' + n
  13. }).join(':')
  14. }
  15. function formatLocation(longitude, latitude) {
  16. if (typeof longitude === 'string' && typeof latitude === 'string') {
  17. longitude = parseFloat(longitude)
  18. latitude = parseFloat(latitude)
  19. }
  20. longitude = longitude.toFixed(2)
  21. latitude = latitude.toFixed(2)
  22. return {
  23. longitude: longitude.toString().split('.'),
  24. latitude: latitude.toString().split('.')
  25. }
  26. }
  27. function fib(n) {
  28. if (n < 1) return 0
  29. if (n <= 2) return 1
  30. return fib(n - 1) + fib(n - 2)
  31. }
  32. function formatLeadingZeroNumber(n, digitNum = 2) {
  33. n = n.toString()
  34. const needNum = Math.max(digitNum - n.length, 0)
  35. return new Array(needNum).fill(0).join('') + n
  36. }
  37. function formatDateTime(date, withMs = false) {
  38. const year = date.getFullYear()
  39. const month = date.getMonth() + 1
  40. const day = date.getDate()
  41. const hour = date.getHours()
  42. const minute = date.getMinutes()
  43. const second = date.getSeconds()
  44. const ms = date.getMilliseconds()
  45. let ret = [year, month, day].map(value => formatLeadingZeroNumber(value, 2)).join('-') +
  46. ' ' + [hour, minute, second].map(value => formatLeadingZeroNumber(value, 2)).join(':')
  47. if (withMs) {
  48. ret += '.' + formatLeadingZeroNumber(ms, 3)
  49. }
  50. return ret
  51. }
  52. function compareVersion(v1, v2) {
  53. v1 = v1.split('.')
  54. v2 = v2.split('.')
  55. const len = Math.max(v1.length, v2.length)
  56. while (v1.length < len) {
  57. v1.push('0')
  58. }
  59. while (v2.length < len) {
  60. v2.push('0')
  61. }
  62. for (let i = 0; i < len; i++) {
  63. const num1 = parseInt(v1[i], 10)
  64. const num2 = parseInt(v2[i], 10)
  65. if (num1 > num2) {
  66. return 1
  67. } else if (num1 < num2) {
  68. return -1
  69. }
  70. }
  71. return 0
  72. }
  73. module.exports = {
  74. formatTime,
  75. formatLocation,
  76. fib,
  77. formatDateTime,
  78. compareVersion
  79. }