Skip to content

Commit

Permalink
Bug 1670033 - Part 7: Implement "unit" support for the "Intl Enumerat…
Browse files Browse the repository at this point in the history
…ion API" proposal. r=tcampbell

Differential Revision: https://phabricator.services.mozilla.com/D120607
  • Loading branch information
anba committed Aug 27, 2021
1 parent 415ecb6 commit 9df1f02
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
22 changes: 22 additions & 0 deletions js/src/builtin/intl/IntlObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#include "builtin/intl/DateTimeFormat.h"
#include "builtin/intl/FormatBuffer.h"
#include "builtin/intl/LanguageTag.h"
#include "builtin/intl/MeasureUnitGenerated.h"
#include "builtin/intl/NumberFormat.h"
#include "builtin/intl/NumberingSystemsGenerated.h"
#include "builtin/intl/PluralRules.h"
Expand Down Expand Up @@ -1232,6 +1233,25 @@ static ArrayObject* AvailableTimeZones(JSContext* cx) {
return CreateArrayFromList(cx, &timeZones);
}

template <size_t N>
constexpr auto MeasurementUnitNames(const MeasureUnit (&units)[N]) {
std::array<const char*, N> array = {};
for (size_t i = 0; i < N; ++i) {
array[i] = units[i].name;
}
return array;
}

/**
* AvailableUnits ( )
*/
static ArrayObject* AvailableUnits(JSContext* cx) {
static constexpr auto simpleMeasureUnitNames =
MeasurementUnitNames(simpleMeasureUnits);

return CreateArrayFromSortedList(cx, simpleMeasureUnitNames);
}

bool js::intl_SupportedValuesOf(JSContext* cx, unsigned argc, JS::Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 1);
Expand All @@ -1253,6 +1273,8 @@ bool js::intl_SupportedValuesOf(JSContext* cx, unsigned argc, JS::Value* vp) {
list = AvailableNumberingSystems(cx);
} else if (StringEqualsLiteral(key, "timeZone")) {
list = AvailableTimeZones(cx);
} else if (StringEqualsLiteral(key, "unit")) {
list = AvailableUnits(cx);
} else {
ReportBadKey(cx, key);
return false;
Expand Down
20 changes: 20 additions & 0 deletions js/src/tests/non262/Intl/supportedValuesOf-unit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// |reftest| skip-if(!this.hasOwnProperty("Intl"))

const units = Intl.supportedValuesOf("unit");

assertEq(new Set(units).size, units.length, "No duplicates are present");
assertEqArray(units, [...units].sort(), "The list is sorted");

const unitRE = /^[a-z]+(-[a-z]+)*$/;
for (let unit of units) {
assertEq(unitRE.test(unit), true, `${unit} is ASCII lower-case, separated by hyphens`);
assertEq(unit.includes("-per-"), false, `${unit} is a simple unit identifier`);
}

for (let unit of units) {
let obj = new Intl.NumberFormat("en", {style: "unit", unit});
assertEq(obj.resolvedOptions().unit, unit, `${unit} is supported by NumberFormat`);
}

if (typeof reportCompare === "function")
reportCompare(true, true);

0 comments on commit 9df1f02

Please sign in to comment.