c70527868404036ae6e6354f7004fdc54ea9b6d40ceb0db194a99a6c4a8e0e69f8b64e85fa9f99c73bd97bc7e1fb38bb38f3f6d48b00b494a15a46dfab2884 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /**
  2. * Take input from [0, n] and return it as [0, 1]
  3. * @hidden
  4. */
  5. export function bound01(n, max) {
  6. if (isOnePointZero(n)) {
  7. n = '100%';
  8. }
  9. var isPercent = isPercentage(n);
  10. n = max === 360 ? n : Math.min(max, Math.max(0, parseFloat(n)));
  11. // Automatically convert percentage into number
  12. if (isPercent) {
  13. n = parseInt(String(n * max), 10) / 100;
  14. }
  15. // Handle floating point rounding errors
  16. if (Math.abs(n - max) < 0.000001) {
  17. return 1;
  18. }
  19. // Convert into [0, 1] range if it isn't already
  20. if (max === 360) {
  21. // If n is a hue given in degrees,
  22. // wrap around out-of-range values into [0, 360] range
  23. // then convert into [0, 1].
  24. n = (n < 0 ? (n % max) + max : n % max) / parseFloat(String(max));
  25. }
  26. else {
  27. // If n not a hue given in degrees
  28. // Convert into [0, 1] range if it isn't already.
  29. n = (n % max) / parseFloat(String(max));
  30. }
  31. return n;
  32. }
  33. /**
  34. * Force a number between 0 and 1
  35. * @hidden
  36. */
  37. export function clamp01(val) {
  38. return Math.min(1, Math.max(0, val));
  39. }
  40. /**
  41. * Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
  42. * <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
  43. * @hidden
  44. */
  45. export function isOnePointZero(n) {
  46. return typeof n === 'string' && n.indexOf('.') !== -1 && parseFloat(n) === 1;
  47. }
  48. /**
  49. * Check to see if string passed in is a percentage
  50. * @hidden
  51. */
  52. export function isPercentage(n) {
  53. return typeof n === 'string' && n.indexOf('%') !== -1;
  54. }
  55. /**
  56. * Return a valid alpha value [0,1] with all invalid values being set to 1
  57. * @hidden
  58. */
  59. export function boundAlpha(a) {
  60. a = parseFloat(a);
  61. if (isNaN(a) || a < 0 || a > 1) {
  62. a = 1;
  63. }
  64. return a;
  65. }
  66. /**
  67. * Replace a decimal with it's percentage value
  68. * @hidden
  69. */
  70. export function convertToPercentage(n) {
  71. if (n <= 1) {
  72. return "".concat(Number(n) * 100, "%");
  73. }
  74. return n;
  75. }
  76. /**
  77. * Force a hex value to have 2 characters
  78. * @hidden
  79. */
  80. export function pad2(c) {
  81. return c.length === 1 ? '0' + c : String(c);
  82. }