You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
1.1 KiB

4 years ago
  1. function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
  2. function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); }
  3. function con(n) {
  4. return 0x80 | n & 0x3f;
  5. }
  6. export function encode(str) {
  7. var arr = str.split("").map(function (x) {
  8. return x.charCodeAt(0);
  9. });
  10. return _encode(arr);
  11. }
  12. function _encode(arr) {
  13. if (arr.length === 0) {
  14. return [];
  15. }
  16. var _arr = _toArray(arr),
  17. n = _arr[0],
  18. ns = _arr.slice(1);
  19. if (n < 0) {
  20. throw new Error("utf8");
  21. }
  22. if (n < 0x80) {
  23. return [n].concat(_toConsumableArray(_encode(ns)));
  24. }
  25. if (n < 0x800) {
  26. return [0xc0 | n >>> 6, con(n)].concat(_toConsumableArray(_encode(ns)));
  27. }
  28. if (n < 0x10000) {
  29. return [0xe0 | n >>> 12, con(n >>> 6), con(n)].concat(_toConsumableArray(_encode(ns)));
  30. }
  31. if (n < 0x110000) {
  32. return [0xf0 | n >>> 18, con(n >>> 12), con(n >>> 6), con(n)].concat(_toConsumableArray(_encode(ns)));
  33. }
  34. throw new Error("utf8");
  35. }