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.

54 lines
1.4 KiB

4 years ago
  1. 'use strict';
  2. module.exports = {
  3. wrap: wrapRange,
  4. limit: limitRange,
  5. validate: validateRange,
  6. test: testRange,
  7. curry: curry,
  8. name: name
  9. };
  10. function wrapRange(min, max, value) {
  11. var maxLessMin = max - min;
  12. return ((value - min) % maxLessMin + maxLessMin) % maxLessMin + min;
  13. }
  14. function limitRange(min, max, value) {
  15. return Math.max(min, Math.min(max, value));
  16. }
  17. function validateRange(min, max, value, minExclusive, maxExclusive) {
  18. if (!testRange(min, max, value, minExclusive, maxExclusive)) {
  19. throw new Error(value + ' is outside of range [' + min + ',' + max + ')');
  20. }
  21. return value;
  22. }
  23. function testRange(min, max, value, minExclusive, maxExclusive) {
  24. return !(
  25. value < min ||
  26. value > max ||
  27. (maxExclusive && (value === max)) ||
  28. (minExclusive && (value === min))
  29. );
  30. }
  31. function name(min, max, minExcl, maxExcl) {
  32. return (minExcl ? '(' : '[') + min + ',' + max + (maxExcl ? ')' : ']');
  33. }
  34. function curry(min, max, minExclusive, maxExclusive) {
  35. var boundNameFn = name.bind(null, min, max, minExclusive, maxExclusive);
  36. return {
  37. wrap: wrapRange.bind(null, min, max),
  38. limit: limitRange.bind(null, min, max),
  39. validate: function(value) {
  40. return validateRange(min, max, value, minExclusive, maxExclusive);
  41. },
  42. test: function(value) {
  43. return testRange(min, max, value, minExclusive, maxExclusive);
  44. },
  45. toString: boundNameFn,
  46. name: boundNameFn
  47. };
  48. }