Stage 1 Draft / March 21, 2017

Intl.UnitFormat

1UnitFormat Objects

1.1Abstract Operations for UnitFormat Objects

1.1.1InitializeUnitFormat (unitFormat, locales, options)

The abstract operation InitializeUnitFormat accepts the arguments unitFormat (which must be an object), locales, and options. It initializes unitFormat as a UnitFormat object. It performs the following steps:

  1. If unitFormat.[[initializedIntlObject]] is true, throw a TypeError exception.
  2. Set unitFormat.[[initializedIntlObject]] to true.
  3. Let requestedLocales be ? CanonicalizeLocaleList(locales).
  4. If options is undefined, then
    1. Let options be ObjectCreate(%ObjectPrototype%).
  5. Else
    1. Let options be ToObject(options).
  6. Let opt be a new Record.
  7. Let u be GetOption(options, "unit", "string", «"bestFit", "second", "minute", "hour", "day", "month", "year", "byte", "kilobyte", "megabyte", "gigabyte", "terabyte"», "bestFit").
  8. If u is not "bestFit", then
    1. Let t be GetUnitFormatGroupName(u).
  9. Else,
    1. Let t be GetOption(options, "type", "string", «"regular", "unit"», "regular").
  10. Set unitFormat.[[unit]] to u.
  11. Set unitFormat.[[type]] to t.
  12. Let s be GetOption(options, "style", "string", «"long", "short", "narrow", "long").
  13. Set unitFormat.[[style]] to s.
  14. Let localeData be %UnitFormat%.[[localeData]].
  15. Let r be ResolveLocale(%UnitFormat%.[[availableLocales]], requestedLocales, opt, %UnitFormat%.[[relevantExtensionKeys]], localeData).
  16. Let dataLocale be r.[[dataLocale]].
  17. Let dataLocaleData be Get(localeData, dataLocale).
  18. Let pattern be GetPattern(dataLocaleData, t, u, s).
  19. Set unitFormat.[[pattern]] to be the value of pattern.
  20. Set unitFormat.[[locale]] to the value of r.[[locale]].
  21. Set unitFormat.[[initializedUnitFormat]] to true.
  22. Return unitFormat.
Table 1: List of unit types
Type Unit
duration century
year
month
week
day
hour
minute
second
millisecond
microsecond
nanosecond
length kilometer
meter
decimeter
centimeter
milimeter
micrometer
nanometer
picometer
mile
yard
foot
inch
parsec
light-year
astronomical-unit
furlong
fathom
nautical-mile
mile-scandinavian
area square-kilometer
hectare
square-meter
square-centimeter
square-mile
acre
square-yard
square-foot
square-inch
volume cubic-kilometer
cubic-meter
cubic-centimeter
cubic-mile
cubic-yard
cubic-foot
cubic-inch
megaliter
hectoliter
liter
deciliter
centiliter
milliliter
pint-metric
cup-metric
acre-foot
bushel
gallon
gallon-imperial
quart
pint
cup
fluid-ounce
tablespoon
teaspoon
speed-and-acceleration g-force
meter-per-second-squared
kilometer-per-hour
meter-per-second
mile-per-hour
knot
mass-and-weight metric-ton
kilogram
gram
milligram
microgram
ton
stone
pound
ounce
ounce-troy
carat
energy-and-power kilocalorie
calorie
foodcalorie
kilojoule
joule
kilowatt-hour
gigawatt
megawatt
kilowatt
watt
milliwatt
horsepower
electrical-and-frequency ampere
milliampere
ohm
volt
gigahertz
megahertz
kilohertz
weather hectopascal
millimeter-of-mercury
pound-per-square-inch
inch-hg
millibar
generic
celsius
fahrenheit
kelvin
digital terabyte
terabit
gigabyte
gigabit
megabyte
megabit
kilobyte
kilobit
byte
bit
coordinates east
north
south
west
other-units radian
degree
arc-minute
arc-second
karat
milligram-per-deciliter
millimole-per-liter
liter-per-kilometer
liter-per-100kilometers
mile-per-gallon
mile-per-gallon-imperial
lux

1.1.2DeconstructPattern (pattern, placeables)

The DeconstructPattern abstract operation is called with arguments pattern (which must be a String) and placeables (which must be an Object), and deconstructts the pattern string into a list of parts. Example:

        Input:
          DeconstructPattern("AA{xx}BB{yy}CC", {
            xx: {type: 'hour', value: '15'},
            yy: {type: 'minute', value: '06'}
          });

        Output:
          [
            {type: 'literal', value: 'AA'},
            {type: 'hour', value: '15'},
            {type: 'literal', value: 'BB'},
            {type: 'minute', value: '06'},
            {type: 'literal', value: 'CC'}
          ]
        

  1. Set parts to be the result of pattern.split(//).
  2. Let result be ArrayCreate(0).
  1. Set i to be 0.
  2. Repeat, while i < parts.length
    1. Set part to be parts.[i].
    2. If i % 2 is 0, then
      1. If part.length is > 0, then
        1. result.push({type: 'literal', value: part}).
    3. Else,
      1. Set subst to placeables.[part].
      2. If !subst, then
        1. Throw new Error.
      3. If Array.isArray(subst), then
        1. result.push(...subst).
      4. Else,
        1. result.push(subst).
  3. Return result.

1.1.3CreatePartsFromPattern (unitFormat, value)

The CreatePartsFromPattern abstract operation is called with arguments unitFormat (which must be an object initialized as a UnitFormat) and value (which must be a Number), and creates the corresponding parts according to the effective locale and the formatting options of unitFormat. The following steps are taken:

  1. Let p be ObjectCreate(%ObjectPrototype%).
  2. Set p.["0"] to be new Object { "type": "value", "value": value }.
  3. Return the result of DeconstructPattern(unitFormat.[[pattern]], p).

1.1.4FormatUnit(unitFormat, value)

The FormatUnit abstract operation is called with arguments unitFormat (which must be an object initialized as a UnitFormat) and list (which must be an Array), and performs the following steps:

  1. Let parts be ? CreatePartsFromPattern(unitFormat, value).
  2. Let result be an empty String.
  3. For each part in parts, do:
    1. Set result to a String value produced by concatenating result and part.[[value]].
  4. Return result.

1.1.5FormatUnitToParts(unitFormat, value)

The FormatUnitToParts abstract operation is called with arguments unitFormat (which must be an object initialized as a UnitFormat) and value (which must be a Number), and performs the following steps:

  1. Let parts be ? CreatePartsFromPattern(unitFormat, value).
  2. Let result be ArrayCreate(0).
  3. Let n be 0.
  4. For each part in parts, do:
    1. Let O be ObjectCreate(%ObjectPrototype%).
    2. Perform ? CreateDataPropertyOrThrow(O, "type", part.[[type]]).
    3. Perform ? CreateDataPropertyOrThrow(O, "value", part.[[value]]).
    4. Perform ? CreateDataProperty(result, ? ToString(n), O).
    5. Increment n by 1.
  5. Return result.

1.2The Intl.UnitFormat Constructor

The UnitFormat constructor is a standard built-in property of the Intl object. Behaviour common to all service constructor properties of the Intl object is specified in .

1.2.1Intl.UnitFormat([ locales [, options]])

When the Intl.UnitFormat function is called with optional arguments the following steps are taken:

  1. If NewTarget is undefined, let newTarget be the active function object, else let newTarget be NewTarget.
  2. Let unitFormat be OrdinaryCreateFromConstructor(newTarget, %UnitFormatPrototype%).
  3. Return InitializeUnitFormat(unitFormat, locales, options).

1.3Properties of the Intl.UnitFormat Constructor

The Intl.UnitFormat constructor has the following properties:

1.3.1Intl.UnitFormat.prototype

The value of Intl.UnitFormat.prototype is %UnitFormatPrototype%.

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

1.3.2Intl.UnitFormat.supportedLocalesOf (locales [, options ])

When the supportedLocalesOf method of %UnitFormat% is called, the following steps are taken:

  1. Let availableLocales be %UnitFormat%.[[availableLocales]].
  2. Let requestedLocales be CanonicalizeLocaleList(locales).
  3. Return SupportedLocales(availableLocales, requestedLocales, options).

The value of the length property of the supportedLocalesOf method is 1.

1.3.3Internal slots

The value of the [[relevantExtensionKeys]] internal slot is [].

The value of the [[availableLocales]] internal slot is implementation defined within the constraints described in .

The value of the [[localeData]] internal slot is implementation defined within the constraints described in and the following additional constraints:

  • [[localeData]][locale] must have a formats property for all locale values. The value of this property must be an object, which must have properties with the names of the two list formatting types: "regular" and "unit". Each object must have properties with the names of three formatting styles: "long", "short" and "narrow". Each of those properties must be objects themselves, and each must have properties with names of templates: "2", "start", "middle" and "end. Each of those properties must be a template string as specified in LDML List Format Rules.
Note
It is recommended that implementations use the locale data provided by the Common Locale Data Repository (available at http://cldr.unicode.org/).

1.4Properties of the Intl.UnitFormat Prototype Object

The Intl.UnitFormat prototype object is itself an Intl.UnitFormat instance as specified in 1.5, whose internal slots are set as if it had been constructed by the expression Construct(%UnitFormat%).

In the following descriptions of functions that are properties or [[Get]] attributes of properties of %UnitFormatPrototype%, the phrase "this UnitFormat object" refers to the object that is the this value for the invocation of the function; a TypeError exception is thrown if the this value is not an object or an object that does not have an [[initializedUnitFormat]] internal slot with value true.

1.4.1Intl.UnitFormat.prototype.constructor

The initial value of Intl.UnitFormat.prototype.constructor is %UnitFormat%.

1.4.2Intl.UnitFormat.prototype[ @@toStringTag ]

The initial value of the @@toStringTag property is the string value "Object".

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

1.4.3Intl.UnitFormat.prototype.format ([ value ])

Intl.UnitFormat.prototype.format is an accessor property whose set accessor function is undefined. Its get accessor function performs the following steps:

  1. Let uf be this value.
  2. Assert: Type(uf) is Object and uf has an [[initializedUnitFormat]] internal slot whose value is true.
  3. If value is not provided or is undefined, then
    1. Let value be 0.
  4. Else,
    1. Let value be ? ToNumber(value).
  5. Return ? FormatUnit(uf, value).

1.4.4Intl.UnitFormat.prototype.formatToParts ([ value ])

Intl.UnitFormat.prototype.format is an accessor property whose set accessor function is undefined. Its get accessor function performs the following steps:

  1. Let uf be this value.
  2. Assert: Type(uf) is Object and uf has an [[initializedUnitFormat]] internal slot whose value is true.
  3. If value is not provided or is undefined, then
    1. Let value be 0.
  4. Else,
    1. Let value be ? ToNumber(value).
  5. Return ? FormatUnitToParts(uf, value).

1.4.5Intl.UnitFormat.prototype.resolvedOptions ()

This function provides access to the locale and options computed during initialization of the object.

The function returns a new object whose properties and attributes are set as if constructed by an object literal assigning to each of the following properties the value of the corresponding internal slot of this UnitFormat object (see 1.5): locale and style. Properties whose corresponding internal slots are not present are not assigned.

1.5Properties of Intl.UnitFormat Instances

Intl.UnitFormat instances inherit properties from %UnitFormatPrototype%.

Intl.UnitFormat instances and other objects that have been successfully initialized as a UnitFormat have [[initializedIntlObject]] and [[initializedUnitFormat]] internal slots whose values are true.

Objects that have been successfully initialized as a UnitFormat object also have several internal slots that are computed by the constructor:

  • [[locale]] is a String value with the language tag of the locale whose localization is used by the list format styles.
  • [[style]] is one of the String values "regular", "duration", "duration-short", "duration-narrow", "unit" or "number", identifying the list formatting style used.

Finally, objects that have been successfully initialized as a UnitFormat have a [[boundResolve]] internal slot that caches the function returned by the format accessor (1.4.3).

ACopyright & Software License

Copyright Notice

© 2017 Mozilla, Ecma International

Software License

All Software contained in this document ("Software") is protected by copyright and is being made available under the "BSD License", included below. This Software may be subject to third party rights (rights from parties other than Ecma International), including patent rights, and no licenses under such third party rights are granted under this license even if the third party concerned is a member of Ecma International. SEE THE ECMA CODE OF CONDUCT IN PATENT MATTERS AVAILABLE AT http://www.ecma-international.org/memento/codeofconduct.htm FOR INFORMATION REGARDING THE LICENSING OF PATENT CLAIMS THAT ARE REQUIRED TO IMPLEMENT ECMA INTERNATIONAL STANDARDS.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  3. Neither the name of the authors nor Ecma International may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE ECMA INTERNATIONAL "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ECMA INTERNATIONAL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.