parse-skeleton.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { TokenParser } from './skeleton-parser/token-parser.js';
  2. /**
  3. * Parse an {@link
  4. * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md
  5. * | ICU NumberFormatter skeleton} string into a {@link Skeleton} structure.
  6. *
  7. * @public
  8. * @param src - The skeleton string
  9. * @param onError - Called when the parser encounters a syntax error. The
  10. * function will still return a {@link Skeleton}, but it may not contain
  11. * information for all tokens. If not defined, the error will be thrown
  12. * instead.
  13. *
  14. * @example
  15. * ```js
  16. * import { parseNumberSkeleton } from '@messageformat/number-skeleton'
  17. *
  18. * parseNumberSkeleton('compact-short currency/GBP', console.error)
  19. * // {
  20. * // notation: { style: 'compact-short' },
  21. * // unit: { style: 'currency', currency: 'GBP' }
  22. * // }
  23. * ```
  24. */
  25. export function parseNumberSkeleton(src, onError = error => {
  26. throw error;
  27. }) {
  28. const tokens = [];
  29. for (const part of src.split(' ')) {
  30. if (part) {
  31. const options = part.split('/');
  32. const stem = options.shift() || '';
  33. tokens.push({ stem, options });
  34. }
  35. }
  36. const parser = new TokenParser(onError);
  37. for (const { stem, options } of tokens) {
  38. parser.parseToken(stem, options);
  39. }
  40. return parser.skeleton;
  41. }