Canonicalize.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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 caseFolding = require('../helpers/caseFolding.json');
  8. // https://262.ecma-international.org/6.0/#sec-runtime-semantics-canonicalize-ch
  9. module.exports = function Canonicalize(ch, IgnoreCase, Unicode) {
  10. if (typeof ch !== 'string') {
  11. throw new $TypeError('Assertion failed: `ch` must be a character');
  12. }
  13. if (typeof IgnoreCase !== 'boolean' || typeof Unicode !== 'boolean') {
  14. throw new $TypeError('Assertion failed: `IgnoreCase` and `Unicode` must be Booleans');
  15. }
  16. if (!IgnoreCase) {
  17. return ch; // step 1
  18. }
  19. if (Unicode) { // step 2
  20. if (hasOwn(caseFolding.C, ch)) {
  21. return caseFolding.C[ch];
  22. }
  23. if (hasOwn(caseFolding.S, ch)) {
  24. return caseFolding.S[ch];
  25. }
  26. return ch; // step 2.b
  27. }
  28. var u = $toUpperCase(ch); // step 2
  29. if (u.length !== 1) {
  30. return ch; // step 3
  31. }
  32. var cu = u; // step 4
  33. if ($charCodeAt(ch, 0) >= 128 && $charCodeAt(cu, 0) < 128) {
  34. return ch; // step 5
  35. }
  36. return cu;
  37. };