1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-25 19:37:35 +00:00

LibJS: Implement Intl.NumberFormat.prototype.formatToParts

This commit is contained in:
Timothy Flynn 2021-11-13 11:33:55 -05:00 committed by Linus Groh
parent 40973814e9
commit 3450def494
5 changed files with 975 additions and 0 deletions

View file

@ -5,6 +5,7 @@
*/
#include <AK/Array.h>
#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/GlobalObject.h>
#include <LibJS/Runtime/Intl/NumberFormat.h>
#include <LibJS/Runtime/Intl/NumberFormatFunction.h>
@ -959,6 +960,43 @@ String format_numeric(NumberFormat& number_format, double number)
return result.build();
}
// 15.1.9 FormatNumericToParts ( numberFormat, x ), https://tc39.es/ecma402/#sec-formatnumbertoparts
Array* format_numeric_to_parts(GlobalObject& global_object, NumberFormat& number_format, double number)
{
auto& vm = global_object.vm();
// 1. Let parts be ? PartitionNumberPattern(numberFormat, x).
// Note: Our implementation of PartitionNumberPattern does not throw.
auto parts = partition_number_pattern(number_format, number);
// 2. Let result be ArrayCreate(0).
auto* result = MUST(Array::create(global_object, 0));
// 3. Let n be 0.
size_t n = 0;
// 4. For each Record { [[Type]], [[Value]] } part in parts, do
for (auto& part : parts) {
// a. Let O be OrdinaryObjectCreate(%Object.prototype%).
auto* object = Object::create(global_object, global_object.object_prototype());
// b. Perform ! CreateDataPropertyOrThrow(O, "type", part.[[Type]]).
MUST(object->create_data_property_or_throw(vm.names.type, js_string(vm, part.type)));
// c. Perform ! CreateDataPropertyOrThrow(O, "value", part.[[Value]]).
MUST(object->create_data_property_or_throw(vm.names.value, js_string(vm, move(part.value))));
// d. Perform ! CreateDataPropertyOrThrow(result, ! ToString(n), O).
MUST(result->create_data_property_or_throw(n, object));
// e. Increment n by 1.
++n;
}
// 5. Return result.
return result;
}
static String cut_trailing_zeroes(StringView string, int cut)
{
// These steps are exactly the same between ToRawPrecision and ToRawFixed.