regexp.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. 'use strict';
  2. function alphabetize(str) {
  3. return str
  4. .split('')
  5. .sort()
  6. .join('');
  7. }
  8. /**
  9. * A class representation of the BSON RegExp type.
  10. */
  11. class BSONRegExp {
  12. /**
  13. * Create a RegExp type
  14. *
  15. * @param {string} pattern The regular expression pattern to match
  16. * @param {string} options The regular expression options
  17. */
  18. constructor(pattern, options) {
  19. // Execute
  20. this.pattern = pattern || '';
  21. this.options = options ? alphabetize(options) : '';
  22. // Validate options
  23. for (let i = 0; i < this.options.length; i++) {
  24. if (
  25. !(
  26. this.options[i] === 'i' ||
  27. this.options[i] === 'm' ||
  28. this.options[i] === 'x' ||
  29. this.options[i] === 'l' ||
  30. this.options[i] === 's' ||
  31. this.options[i] === 'u'
  32. )
  33. ) {
  34. throw new Error(`The regular expression option [${this.options[i]}] is not supported`);
  35. }
  36. }
  37. }
  38. /**
  39. * @ignore
  40. */
  41. toExtendedJSON() {
  42. return { $regularExpression: { pattern: this.pattern, options: this.options } };
  43. }
  44. /**
  45. * @ignore
  46. */
  47. static fromExtendedJSON(doc) {
  48. return new BSONRegExp(
  49. doc.$regularExpression.pattern,
  50. doc.$regularExpression.options
  51. .split('')
  52. .sort()
  53. .join('')
  54. );
  55. }
  56. }
  57. Object.defineProperty(BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' });
  58. module.exports = BSONRegExp;