Canonicalize.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $TypeError = GetIntrinsic('%TypeError%');
  4. var callBound = require('call-bind/callBound');
  5. var has = require('has');
  6. var $charCodeAt = callBound('String.prototype.charCodeAt');
  7. var $toUpperCase = callBound('String.prototype.toUpperCase');
  8. var Type = require('./Type');
  9. var caseFolding = require('../helpers/caseFolding');
  10. // https://262.ecma-international.org/6.0/#sec-runtime-semantics-canonicalize-ch
  11. module.exports = function Canonicalize(ch, IgnoreCase, Unicode) {
  12. if (Type(ch) !== 'String') {
  13. throw new $TypeError('Assertion failed: `ch` must be a character');
  14. }
  15. if (Type(IgnoreCase) !== 'Boolean' || Type(Unicode) !== 'Boolean') {
  16. throw new $TypeError('Assertion failed: `IgnoreCase` and `Unicode` must be Booleans');
  17. }
  18. if (!IgnoreCase) {
  19. return ch; // step 1
  20. }
  21. if (Unicode) { // step 2
  22. if (has(caseFolding.C, ch)) {
  23. return caseFolding.C[ch];
  24. }
  25. if (has(caseFolding.S, ch)) {
  26. return caseFolding.S[ch];
  27. }
  28. return ch; // step 2.b
  29. }
  30. var u = $toUpperCase(ch); // step 2
  31. if (u.length !== 1) {
  32. return ch; // step 3
  33. }
  34. var cu = u; // step 4
  35. if ($charCodeAt(ch, 0) >= 128 && $charCodeAt(cu, 0) < 128) {
  36. return ch; // step 5
  37. }
  38. return cu;
  39. };