format-smart.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * @typedef FormatSmartOptions
  3. * @property {boolean} [useNamedReferences=false]
  4. * Prefer named character references (`&`) where possible.
  5. * @property {boolean} [useShortestReferences=false]
  6. * Prefer the shortest possible reference, if that results in less bytes.
  7. * **Note**: `useNamedReferences` can be omitted when using `useShortestReferences`.
  8. * @property {boolean} [omitOptionalSemicolons=false]
  9. * Whether to omit semicolons when possible.
  10. * **Note**: This creates what HTML calls “parse errors” but is otherwise still valid HTML — don’t use this except when building a minifier.
  11. * Omitting semicolons is possible for certain named and numeric references in some cases.
  12. * @property {boolean} [attribute=false]
  13. * Create character references which don’t fail in attributes.
  14. * **Note**: `attribute` only applies when operating dangerously with
  15. * `omitOptionalSemicolons: true`.
  16. */
  17. import {toHexadecimal} from './to-hexadecimal.js'
  18. import {toDecimal} from './to-decimal.js'
  19. import {toNamed} from './to-named.js'
  20. /**
  21. * Configurable ways to encode a character yielding pretty or small results.
  22. *
  23. * @param {number} code
  24. * @param {number} next
  25. * @param {FormatSmartOptions} options
  26. * @returns {string}
  27. */
  28. export function formatSmart(code, next, options) {
  29. let numeric = toHexadecimal(code, next, options.omitOptionalSemicolons)
  30. /** @type {string|undefined} */
  31. let named
  32. if (options.useNamedReferences || options.useShortestReferences) {
  33. named = toNamed(
  34. code,
  35. next,
  36. options.omitOptionalSemicolons,
  37. options.attribute
  38. )
  39. }
  40. // Use the shortest numeric reference when requested.
  41. // A simple algorithm would use decimal for all code points under 100, as
  42. // those are shorter than hexadecimal:
  43. //
  44. // * `c` vs `c` (decimal shorter)
  45. // * `d` vs `d` (equal)
  46. //
  47. // However, because we take `next` into consideration when `omit` is used,
  48. // And it would be possible that decimals are shorter on bigger values as
  49. // well if `next` is hexadecimal but not decimal, we instead compare both.
  50. if (
  51. (options.useShortestReferences || !named) &&
  52. options.useShortestReferences
  53. ) {
  54. const decimal = toDecimal(code, next, options.omitOptionalSemicolons)
  55. if (decimal.length < numeric.length) {
  56. numeric = decimal
  57. }
  58. }
  59. return named &&
  60. (!options.useShortestReferences || named.length < numeric.length)
  61. ? named
  62. : numeric
  63. }