IndexError.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. /**
  2. * Create a range error with the message:
  3. * 'Index out of range (index < min)'
  4. * 'Index out of range (index < max)'
  5. *
  6. * @param {number} index The actual index
  7. * @param {number} [min=0] Minimum index (included)
  8. * @param {number} [max] Maximum index (excluded)
  9. * @extends RangeError
  10. */
  11. export function IndexError(index, min, max) {
  12. if (!(this instanceof IndexError)) {
  13. throw new SyntaxError('Constructor must be called with the new operator');
  14. }
  15. this.index = index;
  16. if (arguments.length < 3) {
  17. this.min = 0;
  18. this.max = min;
  19. } else {
  20. this.min = min;
  21. this.max = max;
  22. }
  23. if (this.min !== undefined && this.index < this.min) {
  24. this.message = 'Index out of range (' + this.index + ' < ' + this.min + ')';
  25. } else if (this.max !== undefined && this.index >= this.max) {
  26. this.message = 'Index out of range (' + this.index + ' > ' + (this.max - 1) + ')';
  27. } else {
  28. this.message = 'Index out of range (' + this.index + ')';
  29. }
  30. this.stack = new Error().stack;
  31. }
  32. IndexError.prototype = new RangeError();
  33. IndexError.prototype.constructor = RangeError;
  34. IndexError.prototype.name = 'IndexError';
  35. IndexError.prototype.isIndexError = true;