Nikolay Vitkov | d76576c | 2024-12-02 14:10:15 | [diff] [blame] | 1 | 'use strict'; |
| 2 | |
| 3 | var $TypeError = require('es-errors/type'); |
| 4 | |
| 5 | var callBound = require('call-bind/callBound'); |
| 6 | var hasOwn = require('hasown'); |
| 7 | |
| 8 | var $charCodeAt = callBound('String.prototype.charCodeAt'); |
| 9 | var $toUpperCase = callBound('String.prototype.toUpperCase'); |
| 10 | |
| 11 | var caseFolding = require('../helpers/caseFolding.json'); |
| 12 | |
| 13 | // https://262.ecma-international.org/6.0/#sec-runtime-semantics-canonicalize-ch |
| 14 | |
| 15 | module.exports = function Canonicalize(ch, IgnoreCase, Unicode) { |
| 16 | if (typeof ch !== 'string') { |
| 17 | throw new $TypeError('Assertion failed: `ch` must be a character'); |
| 18 | } |
| 19 | |
| 20 | if (typeof IgnoreCase !== 'boolean' || typeof Unicode !== 'boolean') { |
| 21 | throw new $TypeError('Assertion failed: `IgnoreCase` and `Unicode` must be Booleans'); |
| 22 | } |
| 23 | |
| 24 | if (!IgnoreCase) { |
| 25 | return ch; // step 1 |
| 26 | } |
| 27 | |
| 28 | if (Unicode) { // step 2 |
| 29 | if (hasOwn(caseFolding.C, ch)) { |
| 30 | return caseFolding.C[ch]; |
| 31 | } |
| 32 | if (hasOwn(caseFolding.S, ch)) { |
| 33 | return caseFolding.S[ch]; |
| 34 | } |
| 35 | return ch; // step 2.b |
| 36 | } |
| 37 | |
| 38 | var u = $toUpperCase(ch); // step 2 |
| 39 | |
| 40 | if (u.length !== 1) { |
| 41 | return ch; // step 3 |
| 42 | } |
| 43 | |
| 44 | var cu = u; // step 4 |
| 45 | |
| 46 | if ($charCodeAt(ch, 0) >= 128 && $charCodeAt(cu, 0) < 128) { |
| 47 | return ch; // step 5 |
| 48 | } |
| 49 | |
| 50 | return cu; |
| 51 | }; |