You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

121 lines
2.5 KiB

4 years ago
  1. var conversions = {
  2. // length
  3. 'px': {
  4. 'px': 1,
  5. 'cm': 96.0/2.54,
  6. 'mm': 96.0/25.4,
  7. 'in': 96,
  8. 'pt': 96.0/72.0,
  9. 'pc': 16
  10. },
  11. 'cm': {
  12. 'px': 2.54/96.0,
  13. 'cm': 1,
  14. 'mm': 0.1,
  15. 'in': 2.54,
  16. 'pt': 2.54/72.0,
  17. 'pc': 2.54/6.0
  18. },
  19. 'mm': {
  20. 'px': 25.4/96.0,
  21. 'cm': 10,
  22. 'mm': 1,
  23. 'in': 25.4,
  24. 'pt': 25.4/72.0,
  25. 'pc': 25.4/6.0
  26. },
  27. 'in': {
  28. 'px': 1.0/96.0,
  29. 'cm': 1.0/2.54,
  30. 'mm': 1.0/25.4,
  31. 'in': 1,
  32. 'pt': 1.0/72.0,
  33. 'pc': 1.0/6.0
  34. },
  35. 'pt': {
  36. 'px': 0.75,
  37. 'cm': 72.0/2.54,
  38. 'mm': 72.0/25.4,
  39. 'in': 72,
  40. 'pt': 1,
  41. 'pc': 12
  42. },
  43. 'pc': {
  44. 'px': 6.0/96.0,
  45. 'cm': 6.0/2.54,
  46. 'mm': 6.0/25.4,
  47. 'in': 6,
  48. 'pt': 6.0/72.0,
  49. 'pc': 1
  50. },
  51. // angle
  52. 'deg': {
  53. 'deg': 1,
  54. 'grad': 0.9,
  55. 'rad': 180/Math.PI,
  56. 'turn': 360
  57. },
  58. 'grad': {
  59. 'deg': 400/360,
  60. 'grad': 1,
  61. 'rad': 200/Math.PI,
  62. 'turn': 400
  63. },
  64. 'rad': {
  65. 'deg': Math.PI/180,
  66. 'grad': Math.PI/200,
  67. 'rad': 1,
  68. 'turn': Math.PI*2
  69. },
  70. 'turn': {
  71. 'deg': 1/360,
  72. 'grad': 1/400,
  73. 'rad': 0.5/Math.PI,
  74. 'turn': 1
  75. },
  76. // time
  77. 's': {
  78. 's': 1,
  79. 'ms': 1/1000
  80. },
  81. 'ms': {
  82. 's': 1000,
  83. 'ms': 1
  84. },
  85. // frequency
  86. 'Hz': {
  87. 'Hz': 1,
  88. 'kHz': 1000
  89. },
  90. 'kHz': {
  91. 'Hz': 1/1000,
  92. 'kHz': 1
  93. },
  94. // resolution
  95. 'dpi': {
  96. 'dpi': 1,
  97. 'dpcm': 1.0/2.54,
  98. 'dppx': 1/96
  99. },
  100. 'dpcm': {
  101. 'dpi': 2.54,
  102. 'dpcm': 1,
  103. 'dppx': 2.54/96.0
  104. },
  105. 'dppx': {
  106. 'dpi': 96,
  107. 'dpcm': 96.0/2.54,
  108. 'dppx': 1
  109. }
  110. };
  111. module.exports = function (value, sourceUnit, targetUnit, precision) {
  112. if (!conversions.hasOwnProperty(targetUnit))
  113. throw new Error("Cannot convert to " + targetUnit);
  114. if (!conversions[targetUnit].hasOwnProperty(sourceUnit))
  115. throw new Error("Cannot convert from " + sourceUnit + " to " + targetUnit);
  116. precision = Math.pow(10, parseInt(precision) || 5);
  117. return Math.round((conversions[targetUnit][sourceUnit] * value) * precision) / precision;
  118. };