PluralRules.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * Copyright (c) 2022-2024, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/Intl/PluralRules.h>
  7. namespace JS::Intl {
  8. JS_DEFINE_ALLOCATOR(PluralRules);
  9. // 16 PluralRules Objects, https://tc39.es/ecma402/#pluralrules-objects
  10. PluralRules::PluralRules(Object& prototype)
  11. : NumberFormatBase(prototype)
  12. {
  13. }
  14. // 16.5.4 ResolvePlural ( pluralRules, n ), https://tc39.es/ecma402/#sec-resolveplural
  15. ::Locale::PluralCategory resolve_plural(PluralRules const& plural_rules, Value number)
  16. {
  17. // 1. If n is not a finite Number, then
  18. if (!number.is_finite_number()) {
  19. // a. Let s be ! ToString(n).
  20. // b. Return the Record { [[PluralCategory]]: "other", [[FormattedString]]: s }.
  21. return ::Locale::PluralCategory::Other;
  22. }
  23. // 2. Let locale be pluralRules.[[Locale]].
  24. // 3. Let type be pluralRules.[[Type]].
  25. // 4. Let res be FormatNumericToString(pluralRules, ℝ(n)).
  26. // 5. Let s be res.[[FormattedString]].
  27. // 6. Let operands be GetOperands(s).
  28. // 7. Let p be PluralRuleSelect(locale, type, n, operands).
  29. // 8. Return the Record { [[PluralCategory]]: p, [[FormattedString]]: s }.
  30. return plural_rules.formatter().select_plural(number.as_double());
  31. }
  32. // 16.5.6 ResolvePluralRange ( pluralRules, x, y ), https://tc39.es/ecma402/#sec-resolveplural
  33. ThrowCompletionOr<::Locale::PluralCategory> resolve_plural_range(VM& vm, PluralRules const& plural_rules, Value start, Value end)
  34. {
  35. // 1. If x is NaN or y is NaN, throw a RangeError exception.
  36. if (start.is_nan())
  37. return vm.throw_completion<RangeError>(ErrorType::NumberIsNaN, "start"sv);
  38. if (end.is_nan())
  39. return vm.throw_completion<RangeError>(ErrorType::NumberIsNaN, "end"sv);
  40. // 2. Let xp be ResolvePlural(pluralRules, x).
  41. // 3. Let yp be ResolvePlural(pluralRules, y).
  42. // 4. If xp.[[FormattedString]] is yp.[[FormattedString]], then
  43. // a. Return xp.[[PluralCategory]].
  44. // 5. Let locale be pluralRules.[[Locale]].
  45. // 6. Let type be pluralRules.[[Type]].
  46. // 7. Return PluralRuleSelectRange(locale, type, xp.[[PluralCategory]], yp.[[PluralCategory]]).
  47. return plural_rules.formatter().select_plural_range(start.as_double(), end.as_double());
  48. }
  49. }