Canonicalize.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. var $TypeError = require('es-errors/type');
  3. var callBound = require('call-bind/callBound');
  4. var hasOwn = require('hasown');
  5. var $charCodeAt = callBound('String.prototype.charCodeAt');
  6. var $toUpperCase = callBound('String.prototype.toUpperCase');
  7. var isRegExpRecord = require('../helpers/records/regexp-record');
  8. var caseFolding = require('../helpers/caseFolding.json');
  9. // https://262.ecma-international.org/14.0/#sec-runtime-semantics-canonicalize-ch
  10. module.exports = function Canonicalize(rer, ch) {
  11. if (!isRegExpRecord(rer)) {
  12. throw new $TypeError('Assertion failed: `rer` must be a RegExp Record');
  13. }
  14. if (typeof ch !== 'string') {
  15. throw new $TypeError('Assertion failed: `ch` must be a character');
  16. }
  17. if (rer['[[Unicode]]'] && rer['[[IgnoreCase]]']) { // step 1
  18. if (hasOwn(caseFolding.C, ch)) {
  19. return caseFolding.C[ch];
  20. }
  21. if (hasOwn(caseFolding.S, ch)) {
  22. return caseFolding.S[ch];
  23. }
  24. return ch; // step 1.b
  25. }
  26. if (!rer['[[IgnoreCase]]']) {
  27. return ch; // step 2
  28. }
  29. var u = $toUpperCase(ch); // step 5
  30. if (u.length !== 1) {
  31. return ch; // step 7
  32. }
  33. var cu = u; // step 8
  34. if ($charCodeAt(ch, 0) >= 128 && $charCodeAt(cu, 0) < 128) {
  35. return ch; // step 9
  36. }
  37. return cu; // step 10
  38. };