포매터가 실제로 어떤 로케일과 옵션을 사용하고 있는지 어떻게 확인하나요?

resolvedOptions() 메서드를 사용하여 모든 Intl 포매터의 실제 구성을 검사합니다

소개

JavaScript에서 Intl 포맷터를 생성할 때, 요청한 옵션이 항상 얻게 되는 옵션과 일치하지는 않습니다. 브라우저는 로케일 협상을 수행하고, 기본값을 채우며, 최종 구성을 만들기 위해 설정을 정규화합니다. resolvedOptions() 메서드를 사용하면 포맷터가 실제로 사용하고 있는 것을 정확히 검사할 수 있습니다.

Intl API의 모든 포맷터에는 resolvedOptions() 메서드가 있습니다. 여기에는 Intl.DateTimeFormat, Intl.NumberFormat, Intl.ListFormat, Intl.PluralRules, Intl.Collator 등이 포함됩니다. 이 메서드는 입력을 처리한 후 포맷터가 최종적으로 사용하게 된 모든 구성 세부 정보가 포함된 객체를 반환합니다.

이 메서드는 주로 디버깅, 브라우저 동작 이해, 현재 환경에서 사용 가능한 기능 감지에 유용합니다.

기본 구문

'resolvedOptions()' 메서드는 매개변수를 받지 않습니다. 포맷터 인스턴스에서 호출하면 객체를 반환합니다.

const formatter = new Intl.DateTimeFormat('en-US');
const options = formatter.resolvedOptions();

console.log(options);
// {
//   locale: 'en-US',
//   calendar: 'gregory',
//   numberingSystem: 'latn',
//   timeZone: 'America/Los_Angeles',
//   ...
// }

반환된 객체는 날짜 포맷터의 경우 최소한 locale, calendar, numberingSystem 속성을 포함하고, 숫자 포맷터의 경우 localenumberingSystem을 포함합니다. 추가 속성은 지정한 옵션과 포맷터 유형이 지원하는 것에 따라 달라집니다.

요청된 옵션이 해결된 옵션과 다른 이유

요청한 옵션이 해결된 옵션과 다를 수 있는 주요 이유는 세 가지입니다.

첫째, 로케일 협상은 정확한 요청이 지원되지 않을 때 사용 가능한 최적의 로케일을 찾습니다. de-AT를 요청했지만 브라우저가 de만 가지고 있다면, 해결된 로케일은 de가 됩니다.

const formatter = new Intl.DateTimeFormat('de-AT-u-ca-buddhist');
const options = formatter.resolvedOptions();

console.log(options.locale);
// 가능한 출력: 'de-AT' 또는 'de'

console.log(options.calendar);
// 가능한 출력: 'gregory' (불교 달력이 지원되지 않는 경우)

둘째, 브라우저는 지정하지 않은 옵션에 대해 기본값을 채웁니다. 이러한 기본값은 로케일별로 다릅니다.

const formatter = new Intl.NumberFormat('en-US');
const options = formatter.resolvedOptions();

console.log(options.style);
// 출력: 'decimal'

console.log(options.minimumFractionDigits);
// 출력: 0

console.log(options.maximumFractionDigits);
// 출력: 3

셋째, 브라우저는 특정 옵션을 표준 형식으로 정규화합니다. dateStyle 또는 timeStyle을 사용하면 브라우저는 이를 해결된 옵션에 포함시키지 않습니다. 대신, 이들이 확장되는 개별 구성 요소 옵션을 포함합니다.

실제 사용 중인 로케일 확인하기

locale 속성은 해결된 옵션에서 포매터가 정확히 어떤 로케일을 사용하고 있는지 알려줍니다. 이는 로케일 협상의 결과입니다.

const formatter = new Intl.DateTimeFormat(['zh-TW', 'zh-CN', 'en-US']);
const options = formatter.resolvedOptions();

console.log(options.locale);
// 목록에서 지원되는 첫 번째 로케일을 출력합니다

유니코드 확장 키워드가 포함된 로케일을 요청하면, 해당 키워드가 지원되지 않거나 별도의 옵션으로 적용된 경우 해결된 로케일에 해당 키워드가 포함되지 않을 수 있습니다.

const formatter = new Intl.NumberFormat('en-US-u-nu-arab');
const options = formatter.resolvedOptions();

console.log(options.locale);
// 출력 가능: 'en-US'

console.log(options.numberingSystem);
// 지원 여부에 따라 'arab' 또는 'latn' 출력 가능

날짜 및 시간 서식 옵션 검사하기

Intl.DateTimeFormat의 경우, 해결된 옵션에는 어떤 날짜 및 시간 구성 요소가 표시되고 어떻게 표시될지에 대한 세부 정보가 포함됩니다.

const formatter = new Intl.DateTimeFormat('en-US', {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  timeZone: 'America/New_York'
});

const options = formatter.resolvedOptions();

console.log(options.year);
// 출력: 'numeric'

console.log(options.month);
// 출력: 'long'

console.log(options.day);
// 출력: 'numeric'

console.log(options.timeZone);
// 출력: 'America/New_York'

console.log(options.calendar);
// 출력: 'gregory'

dateStyle 또는 timeStyle을 사용할 때, 이러한 단축키는 해결된 옵션에 포함되지 않습니다. 브라우저는 로케일에 따라 이를 개별 구성 요소 옵션으로 확장합니다.

const formatter = new Intl.DateTimeFormat('en-US', {
  dateStyle: 'full'
});

const options = formatter.resolvedOptions();

console.log(options.dateStyle);
// 출력: undefined

console.log(options.weekday);
// 출력: 'long'

console.log(options.year);
// 출력: 'numeric'

console.log(options.month);
// 출력: 'long'

console.log(options.day);
// 출력: 'numeric'

옵션 없이 날짜 포매터를 생성하면, 해결된 옵션은 브라우저가 해당 로케일에 대해 기본값으로 선택한 것을 보여줍니다.

const formatter = new Intl.DateTimeFormat('ja-JP');
const options = formatter.resolvedOptions();

console.log(options);
// 일본어 로케일에 대한 기본 날짜 구성 요소 옵션 표시

숫자 서식 옵션 검사하기

'Intl.NumberFormat'의 경우, 해결된 옵션은 스타일, 정밀도, 그룹화 및 기타 서식 세부 정보를 알려줍니다.

const formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD'
});

const options = formatter.resolvedOptions();

console.log(options.style);
// 출력: 'currency'

console.log(options.currency);
// 출력: 'USD'

console.log(options.currencyDisplay);
// 출력: 'symbol'

console.log(options.minimumFractionDigits);
// 출력: 2

console.log(options.maximumFractionDigits);
// 출력: 2

통화만 지정했지만 브라우저가 'currencyDisplay'와 소수 자릿수에 대한 기본값을 채웠음을 확인할 수 있습니다.

반올림 옵션을 사용할 때, 해결된 옵션은 숫자가 어떻게 반올림될지 정확히 보여줍니다.

const formatter = new Intl.NumberFormat('en-US', {
  minimumSignificantDigits: 3,
  maximumSignificantDigits: 5
});

const options = formatter.resolvedOptions();

console.log(options.minimumSignificantDigits);
// 출력: 3

console.log(options.maximumSignificantDigits);
// 출력: 5

다른 포맷터 유형 검사하기

'resolvedOptions()' 메서드는 모든 Intl 포맷터에서 동일한 방식으로 작동합니다.

'Intl.ListFormat'의 경우, 유형과 스타일을 보여줍니다.

const formatter = new Intl.ListFormat('en-US', {
  style: 'long',
  type: 'conjunction'
});

const options = formatter.resolvedOptions();

console.log(options.locale);
// 출력: 'en-US'

console.log(options.style);
// 출력: 'long'

console.log(options.type);
// 출력: 'conjunction'

'Intl.PluralRules'의 경우, 유형과 최소/최대 자릿수를 보여줍니다.

const formatter = new Intl.PluralRules('en-US', {
  type: 'ordinal'
});

const options = formatter.resolvedOptions();

console.log(options.locale);
// 출력: 'en-US'

console.log(options.type);
// 출력: 'ordinal'

console.log(options.minimumIntegerDigits);
// 출력: 1

resolvedOptions()의 일반적인 사용 사례

가장 일반적인 사용 사례는 디버깅입니다. 형식이 지정된 출력이 예상대로 보이지 않을 때, 'resolvedOptions()'는 포맷터가 실제로 무엇을 하고 있는지 이해하는 데 도움이 됩니다.

const formatter = new Intl.DateTimeFormat('en-US', {
  dateStyle: 'medium'
});

console.log(formatter.format(new Date()));
// 출력 확인

console.log(formatter.resolvedOptions());
// 해당 출력을 생성한 정확한 옵션 확인

또 다른 사용 사례는 기능 감지입니다. 특정 달력, 번호 체계 또는 기타 기능이 지원되는지 요청하고 실제로 해결된 내용을 확인하여 확인할 수 있습니다.

const formatter = new Intl.DateTimeFormat('en-US', {
  calendar: 'islamic'
});

const options = formatter.resolvedOptions();

if (options.calendar === 'islamic') {
  console.log('이슬람력이 지원됩니다');
} else {
  console.log('이슬람력이 지원되지 않습니다, ' + options.calendar + '을(를) 사용합니다');
}

또한 'resolvedOptions()'를 사용하여 사용자의 로케일 환경 설정을 가져올 수 있습니다. 로케일 인수 없이 포맷터를 생성하면 브라우저는 사용자의 환경 설정을 사용합니다.

const formatter = new Intl.DateTimeFormat();
const options = formatter.resolvedOptions();

console.log(options.locale);
// 출력: 사용자가 선호하는 로케일

console.log(options.timeZone);
// 출력: 사용자의 시간대

console.log(options.hourCycle);
// 출력: 사용자의 시간 주기 환경 설정(12시간 또는 24시간)

마지막으로, 해결된 옵션을 사용하여 동일한 포맷터를 다시 만들 수 있습니다. 반환된 객체는 생성자에 다시 전달될 수 있습니다.

const formatter1 = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD'
});

const options = formatter1.resolvedOptions();

const formatter2 = new Intl.NumberFormat(options.locale, options);

// formatter2는 formatter1과 동일하게 숫자 형식을 지정합니다

핵심 요약

'resolvedOptions()' 메서드는 포매터가 실제로 사용 중인 구성이 포함된 객체를 반환합니다. 이 구성은 로케일 협상, 기본값 및 정규화로 인해 요청한 것과 다를 수 있습니다.

모든 Intl 포매터에는 이 메서드가 있습니다. 매개변수 없이 호출하면 'locale', 'calendar', 'numberingSystem' 및 포매터별 옵션과 같은 속성이 있는 객체를 받습니다.

'resolvedOptions()'는 주로 포매터 동작 디버깅, 사용 가능한 기능 감지 및 브라우저가 옵션을 어떻게 해석했는지 이해하는 데 사용합니다. 반환된 객체는 동일한 포매터를 재생성하거나 사용자 환경설정을 검사하는 데도 사용할 수 있습니다.