CoolFace
Apppublic

AK-21/Graphite-Industrial-Intelligence

sourceHugging Faceupdated 3mo agoView on Hugging Face
0likes
format-smart.js70 linesDownload Raw Back to util
1/**2 * @typedef FormatSmartOptions3 * @property {boolean} [useNamedReferences=false]4 *   Prefer named character references (`&amp;`) 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 with15 *   `omitOptionalSemicolons: true`.16 */17 18import {toHexadecimal} from './to-hexadecimal.js'19import {toDecimal} from './to-decimal.js'20import {toNamed} from './to-named.js'21 22/**23 * Configurable ways to encode a character yielding pretty or small results.24 *25 * @param {number} code26 * @param {number} next27 * @param {FormatSmartOptions} options28 * @returns {string}29 */30export function formatSmart(code, next, options) {31  let numeric = toHexadecimal(code, next, options.omitOptionalSemicolons)32  /** @type {string|undefined} */33  let named34 35  if (options.useNamedReferences || options.useShortestReferences) {36    named = toNamed(37      code,38      next,39      options.omitOptionalSemicolons,40      options.attribute41    )42  }43 44  // Use the shortest numeric reference when requested.45  // A simple algorithm would use decimal for all code points under 100, as46  // those are shorter than hexadecimal:47  //48  // * `&#99;` vs `&#x63;` (decimal shorter)49  // * `&#100;` vs `&#x64;` (equal)50  //51  // However, because we take `next` into consideration when `omit` is used,52  // And it would be possible that decimals are shorter on bigger values as53  // well if `next` is hexadecimal but not decimal, we instead compare both.54  if (55    (options.useShortestReferences || !named) &&56    options.useShortestReferences57  ) {58    const decimal = toDecimal(code, next, options.omitOptionalSemicolons)59 60    if (decimal.length < numeric.length) {61      numeric = decimal62    }63  }64 65  return named &&66    (!options.useShortestReferences || named.length < numeric.length)67    ? named68    : numeric69}70