private static Optional getParentLocaleBasedOnLocaleAndScript()

in locales-utils/src/main/java/com/spotify/i18n/locales/utils/hierarchy/LocalesHierarchyUtils.java [236:264]


  private static Optional<ULocale> getParentLocaleBasedOnLocaleAndScript(final ULocale locale) {
    // We retrieve the script from the given locale
    final String localeScript = getLocaleScript(locale);
    // We retrieve the script from the fallback locale
    final String parentLocaleScript = getLocaleScript(locale.getFallback());

    if (localeScript.equals(parentLocaleScript)) {
      // If they are a match, we can safely return the fallback.
      return Optional.of(locale.getFallback());
    } else {
      final ULocale localeWithScriptOverride =
          new Builder()
              // Build with the base language tag
              .setLanguageTag(locale.toLanguageTag())
              // Override the script only
              .setScript(localeScript)
              .build();
      if (isSameLocale(locale, localeWithScriptOverride)) {
        // This is most likely a locale that is not available in CLDR, with a wrong combination
        // of language code and script code.
        return Optional.empty();
      } else {
        // When they are not a match, we call the same method by force-feeding the script
        // identifier to the given locale. Ex: for zh-TW, we will be calling this same method,
        // with the overridden zh-Hant-TW locale.
        return getParentLocale(localeWithScriptOverride);
      }
    }
  }