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.

81 lines
1.8 KiB

4 years ago
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = function (number, unit, { time, length, angle }) {
  6. let value = dropLeadingZero(number) + (unit ? unit : '');
  7. let converted;
  8. if (length !== false && unit.toLowerCase() in lengthConv) {
  9. converted = transform(number, unit, lengthConv);
  10. }
  11. if (time !== false && unit.toLowerCase() in timeConv) {
  12. converted = transform(number, unit, timeConv);
  13. }
  14. if (angle !== false && unit.toLowerCase() in angleConv) {
  15. converted = transform(number, unit, angleConv);
  16. }
  17. if (converted && converted.length < value.length) {
  18. value = converted;
  19. }
  20. return value;
  21. };
  22. const lengthConv = {
  23. in: 96,
  24. px: 1,
  25. pt: 4 / 3,
  26. pc: 16
  27. };
  28. const timeConv = {
  29. s: 1000,
  30. ms: 1
  31. };
  32. const angleConv = {
  33. turn: 360,
  34. deg: 1
  35. };
  36. function dropLeadingZero(number) {
  37. const value = String(number);
  38. if (number % 1) {
  39. if (value[0] === '0') {
  40. return value.slice(1);
  41. }
  42. if (value[0] === '-' && value[1] === '0') {
  43. return '-' + value.slice(2);
  44. }
  45. }
  46. return value;
  47. }
  48. function transform(number, unit, conversion) {
  49. const lowerCasedUnit = unit.toLowerCase();
  50. let one, base;
  51. let convertionUnits = Object.keys(conversion).filter(u => {
  52. if (conversion[u] === 1) {
  53. one = u;
  54. }
  55. return lowerCasedUnit !== u;
  56. });
  57. if (lowerCasedUnit === one) {
  58. base = number / conversion[lowerCasedUnit];
  59. } else {
  60. base = number * conversion[lowerCasedUnit];
  61. }
  62. return convertionUnits.map(u => dropLeadingZero(base / conversion[u]) + u).reduce((a, b) => a.length < b.length ? a : b);
  63. }
  64. module.exports = exports['default'];