index.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. }