regExpUtils.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright (C) 2017 Mathias Bynens. All rights reserved.
  2. // This code is governed by the BSD license found in the LICENSE file.
  3. /*---
  4. description: |
  5. Collection of functions used to assert the correctness of RegExp objects.
  6. ---*/
  7. function buildString({ loneCodePoints, ranges }) {
  8. const CHUNK_SIZE = 10000;
  9. let result = String.fromCodePoint(...loneCodePoints);
  10. for (const [start, end] of ranges) {
  11. const codePoints = [];
  12. for (let length = 0, codePoint = start; codePoint <= end; codePoint++) {
  13. codePoints[length++] = codePoint;
  14. if (length === CHUNK_SIZE) {
  15. result += String.fromCodePoint(...codePoints);
  16. codePoints.length = length = 0;
  17. }
  18. }
  19. result += String.fromCodePoint(...codePoints);
  20. }
  21. return result;
  22. }
  23. function testPropertyEscapes(regex, string, expression) {
  24. if (!regex.test(string)) {
  25. for (const symbol of string) {
  26. const hex = symbol
  27. .codePointAt(0)
  28. .toString(16)
  29. .toUpperCase()
  30. .padStart(6, "0");
  31. assert(
  32. regex.test(symbol),
  33. `\`${ expression }\` should match U+${ hex } (\`${ symbol }\`)`
  34. );
  35. }
  36. }
  37. }
  38. // Returns a function that will validate RegExp match result
  39. //
  40. // Example:
  41. //
  42. // var validate = matchValidator(['b'], 1, 'abc');
  43. // validate(/b/.exec('abc'));
  44. //
  45. function matchValidator(expectedEntries, expectedIndex, expectedInput) {
  46. return function(match) {
  47. assert.compareArray(match, expectedEntries, 'Match entries');
  48. assert.sameValue(match.index, expectedIndex, 'Match index');
  49. assert.sameValue(match.input, expectedInput, 'Match input');
  50. }
  51. }