Latest Threat Research:SANDWORM_MODE: Shai-Hulud-Style npm Worm Hijacks CI Workflows and Poisons AI Toolchains.Details
Socket
Book a DemoInstallSign in
Socket

@formatjs/ecma402-abstract

Package Overview
Dependencies
Maintainers
3
Versions
92
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@formatjs/ecma402-abstract - npm Package Compare versions

Comparing version
3.0.7
to
3.0.8
+55
-55
262.d.ts

@@ -1,67 +0,67 @@

import { Decimal } from 'decimal.js';
import { Decimal } from "decimal.js";
/**
* https://tc39.es/ecma262/#sec-tostring
*/
* https://tc39.es/ecma262/#sec-tostring
*/
export declare function ToString(o: unknown): string;
/**
* https://tc39.es/ecma262/#sec-tonumber
* @param val
*/
* https://tc39.es/ecma262/#sec-tonumber
* @param val
*/
export declare function ToNumber(arg: any): Decimal;
/**
* https://tc39.es/ecma262/#sec-timeclip
* @param time
*/
* https://tc39.es/ecma262/#sec-timeclip
* @param time
*/
export declare function TimeClip(time: Decimal): Decimal;
/**
* https://tc39.es/ecma262/#sec-toobject
* @param arg
*/
* https://tc39.es/ecma262/#sec-toobject
* @param arg
*/
export declare function ToObject<T>(arg: T): T extends null ? never : T extends undefined ? never : T;
/**
* https://www.ecma-international.org/ecma-262/11.0/index.html#sec-samevalue
* @param x
* @param y
*/
* https://www.ecma-international.org/ecma-262/11.0/index.html#sec-samevalue
* @param x
* @param y
*/
export declare function SameValue(x: any, y: any): boolean;
/**
* https://www.ecma-international.org/ecma-262/11.0/index.html#sec-arraycreate
* @param len
*/
* https://www.ecma-international.org/ecma-262/11.0/index.html#sec-arraycreate
* @param len
*/
export declare function ArrayCreate<T = any>(len: number): T[];
/**
* https://www.ecma-international.org/ecma-262/11.0/index.html#sec-hasownproperty
* @param o
* @param prop
*/
* https://www.ecma-international.org/ecma-262/11.0/index.html#sec-hasownproperty
* @param o
* @param prop
*/
export declare function HasOwnProperty(o: object, prop: string): boolean;
/**
* https://www.ecma-international.org/ecma-262/11.0/index.html#sec-type
* @param x
*/
export declare function Type(x: any): 'Null' | 'Undefined' | 'Object' | 'Number' | 'Boolean' | 'String' | 'Symbol' | 'BigInt' | undefined;
* https://www.ecma-international.org/ecma-262/11.0/index.html#sec-type
* @param x
*/
export declare function Type(x: any): "Null" | "Undefined" | "Object" | "Number" | "Boolean" | "String" | "Symbol" | "BigInt" | undefined;
/**
* https://tc39.es/ecma262/#eqn-Day
* @param t
*/
* https://tc39.es/ecma262/#eqn-Day
* @param t
*/
export declare function Day(t: number): number;
/**
* https://tc39.es/ecma262/#sec-week-day
* @param t
*/
* https://tc39.es/ecma262/#sec-week-day
* @param t
*/
export declare function WeekDay(t: number): number;
/**
* https://tc39.es/ecma262/#sec-year-number
* @param y
*/
* https://tc39.es/ecma262/#sec-year-number
* @param y
*/
export declare function DayFromYear(y: number): number;
/**
* https://tc39.es/ecma262/#sec-year-number
* @param y
*/
* https://tc39.es/ecma262/#sec-year-number
* @param y
*/
export declare function TimeFromYear(y: number): number;
/**
* https://tc39.es/ecma262/#sec-year-number
* @param t
*/
* https://tc39.es/ecma262/#sec-year-number
* @param t
*/
export declare function YearFromTime(t: number): number;

@@ -72,5 +72,5 @@ export declare function DaysInYear(y: number): 365 | 366;

/**
* https://tc39.es/ecma262/#sec-month-number
* @param t
*/
* https://tc39.es/ecma262/#sec-month-number
* @param t
*/
export declare function MonthFromTime(t: number): 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11;

@@ -82,14 +82,14 @@ export declare function DateFromTime(t: number): number;

/**
* The abstract operation OrdinaryHasInstance implements
* the default algorithm for determining if an object O
* inherits from the instance object inheritance path
* provided by constructor C.
* @param C class
* @param O object
* @param internalSlots internalSlots
*/
* The abstract operation OrdinaryHasInstance implements
* the default algorithm for determining if an object O
* inherits from the instance object inheritance path
* provided by constructor C.
* @param C class
* @param O object
* @param internalSlots internalSlots
*/
export declare function OrdinaryHasInstance(C: object, O: any, internalSlots?: {
boundTargetFunction: any;
boundTargetFunction: any;
}): boolean;
export declare function msFromTime(t: number): number;
export declare function ToPrimitive<T extends 'string' | 'number' = 'string' | 'number'>(input: any, preferredType: T): string | number | boolean | undefined | null;
export declare function ToPrimitive<T extends "string" | "number" = "string" | "number">(input: any, preferredType: T): string | number | boolean | undefined | null;
+322
-327

@@ -1,400 +0,395 @@

import { Decimal } from 'decimal.js';
import { ZERO } from './constants.js';
import { invariant } from './utils.js';
import { Decimal } from "decimal.js";
import { ZERO } from "./constants.js";
import { invariant } from "./utils.js";
/**
* https://tc39.es/ecma262/#sec-tostring
*/
* https://tc39.es/ecma262/#sec-tostring
*/
export function ToString(o) {
// Only symbol is irregular...
if (typeof o === 'symbol') {
throw TypeError('Cannot convert a Symbol value to a string');
}
return String(o);
// Only symbol is irregular...
if (typeof o === "symbol") {
throw TypeError("Cannot convert a Symbol value to a string");
}
return String(o);
}
/**
* https://tc39.es/ecma262/#sec-tonumber
* @param val
*/
* https://tc39.es/ecma262/#sec-tonumber
* @param val
*/
export function ToNumber(arg) {
if (typeof arg === 'number') {
return new Decimal(arg);
}
invariant(typeof arg !== 'bigint' && typeof arg !== 'symbol', 'BigInt and Symbol are not supported', TypeError);
if (arg === undefined) {
return new Decimal(NaN);
}
if (arg === null || arg === 0) {
return ZERO;
}
if (arg === true) {
return new Decimal(1);
}
if (typeof arg === 'string') {
try {
return new Decimal(arg);
}
catch (_a) {
return new Decimal(NaN);
}
}
invariant(typeof arg === 'object', 'object expected', TypeError);
var primValue = ToPrimitive(arg, 'number');
invariant(typeof primValue !== 'object', 'object expected', TypeError);
return ToNumber(primValue);
if (typeof arg === "number") {
return new Decimal(arg);
}
invariant(typeof arg !== "bigint" && typeof arg !== "symbol", "BigInt and Symbol are not supported", TypeError);
if (arg === undefined) {
return new Decimal(NaN);
}
if (arg === null || arg === 0) {
return ZERO;
}
if (arg === true) {
return new Decimal(1);
}
if (typeof arg === "string") {
try {
return new Decimal(arg);
} catch {
return new Decimal(NaN);
}
}
invariant(typeof arg === "object", "object expected", TypeError);
let primValue = ToPrimitive(arg, "number");
invariant(typeof primValue !== "object", "object expected", TypeError);
return ToNumber(primValue);
}
/**
* https://tc39.es/ecma262/#sec-tointeger
* @param n
*/
* https://tc39.es/ecma262/#sec-tointeger
* @param n
*/
function ToInteger(n) {
var number = ToNumber(n);
if (number.isNaN() || number.isZero()) {
return ZERO;
}
if (number.isFinite()) {
return number;
}
var integer = number.abs().floor();
if (number.isNegative()) {
integer = integer.negated();
}
return integer;
const number = ToNumber(n);
if (number.isNaN() || number.isZero()) {
return ZERO;
}
if (number.isFinite()) {
return number;
}
let integer = number.abs().floor();
if (number.isNegative()) {
integer = integer.negated();
}
return integer;
}
/**
* https://tc39.es/ecma262/#sec-timeclip
* @param time
*/
* https://tc39.es/ecma262/#sec-timeclip
* @param time
*/
export function TimeClip(time) {
if (!time.isFinite()) {
return new Decimal(NaN);
}
if (time.abs().greaterThan(8.64 * 1e15)) {
return new Decimal(NaN);
}
return ToInteger(time);
if (!time.isFinite()) {
return new Decimal(NaN);
}
if (time.abs().greaterThan(8.64 * 0x38d7ea4c68000)) {
return new Decimal(NaN);
}
return ToInteger(time);
}
/**
* https://tc39.es/ecma262/#sec-toobject
* @param arg
*/
* https://tc39.es/ecma262/#sec-toobject
* @param arg
*/
export function ToObject(arg) {
if (arg == null) {
throw new TypeError('undefined/null cannot be converted to object');
}
return Object(arg);
if (arg == null) {
throw new TypeError("undefined/null cannot be converted to object");
}
return Object(arg);
}
/**
* https://www.ecma-international.org/ecma-262/11.0/index.html#sec-samevalue
* @param x
* @param y
*/
* https://www.ecma-international.org/ecma-262/11.0/index.html#sec-samevalue
* @param x
* @param y
*/
export function SameValue(x, y) {
if (Object.is) {
return Object.is(x, y);
}
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
}
// Step 6.a: NaN == NaN
return x !== x && y !== y;
if (Object.is) {
return Object.is(x, y);
}
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
}
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
/**
* https://www.ecma-international.org/ecma-262/11.0/index.html#sec-arraycreate
* @param len
*/
* https://www.ecma-international.org/ecma-262/11.0/index.html#sec-arraycreate
* @param len
*/
export function ArrayCreate(len) {
return Array.from({ length: len });
return Array.from({ length: len });
}
/**
* https://www.ecma-international.org/ecma-262/11.0/index.html#sec-hasownproperty
* @param o
* @param prop
*/
* https://www.ecma-international.org/ecma-262/11.0/index.html#sec-hasownproperty
* @param o
* @param prop
*/
export function HasOwnProperty(o, prop) {
return Object.prototype.hasOwnProperty.call(o, prop);
return Object.prototype.hasOwnProperty.call(o, prop);
}
/**
* https://www.ecma-international.org/ecma-262/11.0/index.html#sec-type
* @param x
*/
* https://www.ecma-international.org/ecma-262/11.0/index.html#sec-type
* @param x
*/
export function Type(x) {
if (x === null) {
return 'Null';
}
if (typeof x === 'undefined') {
return 'Undefined';
}
if (typeof x === 'function' || typeof x === 'object') {
return 'Object';
}
if (typeof x === 'number') {
return 'Number';
}
if (typeof x === 'boolean') {
return 'Boolean';
}
if (typeof x === 'string') {
return 'String';
}
if (typeof x === 'symbol') {
return 'Symbol';
}
if (typeof x === 'bigint') {
return 'BigInt';
}
if (x === null) {
return "Null";
}
if (typeof x === "undefined") {
return "Undefined";
}
if (typeof x === "function" || typeof x === "object") {
return "Object";
}
if (typeof x === "number") {
return "Number";
}
if (typeof x === "boolean") {
return "Boolean";
}
if (typeof x === "string") {
return "String";
}
if (typeof x === "symbol") {
return "Symbol";
}
if (typeof x === "bigint") {
return "BigInt";
}
}
var MS_PER_DAY = 86400000;
const MS_PER_DAY = 864e5;
/**
* https://www.ecma-international.org/ecma-262/11.0/index.html#eqn-modulo
* @param x
* @param y
* @return k of the same sign as y
*/
* https://www.ecma-international.org/ecma-262/11.0/index.html#eqn-modulo
* @param x
* @param y
* @return k of the same sign as y
*/
function mod(x, y) {
return x - Math.floor(x / y) * y;
return x - Math.floor(x / y) * y;
}
/**
* https://tc39.es/ecma262/#eqn-Day
* @param t
*/
* https://tc39.es/ecma262/#eqn-Day
* @param t
*/
export function Day(t) {
return Math.floor(t / MS_PER_DAY);
return Math.floor(t / MS_PER_DAY);
}
/**
* https://tc39.es/ecma262/#sec-week-day
* @param t
*/
* https://tc39.es/ecma262/#sec-week-day
* @param t
*/
export function WeekDay(t) {
return mod(Day(t) + 4, 7);
return mod(Day(t) + 4, 7);
}
/**
* https://tc39.es/ecma262/#sec-year-number
* @param y
*/
* https://tc39.es/ecma262/#sec-year-number
* @param y
*/
export function DayFromYear(y) {
if (y < 100) {
// Date.UTC parses 0 - 99 as 1900 - 1999
var date = new Date(0);
date.setUTCFullYear(y, 0, 1);
date.setUTCHours(0, 0, 0, 0);
return date.getTime() / MS_PER_DAY;
}
return Date.UTC(y, 0) / MS_PER_DAY;
if (y < 100) {
// Date.UTC parses 0 - 99 as 1900 - 1999
const date = new Date(0);
date.setUTCFullYear(y, 0, 1);
date.setUTCHours(0, 0, 0, 0);
return date.getTime() / MS_PER_DAY;
}
return Date.UTC(y, 0) / MS_PER_DAY;
}
/**
* https://tc39.es/ecma262/#sec-year-number
* @param y
*/
* https://tc39.es/ecma262/#sec-year-number
* @param y
*/
export function TimeFromYear(y) {
return Date.UTC(y, 0);
return Date.UTC(y, 0);
}
/**
* https://tc39.es/ecma262/#sec-year-number
* @param t
*/
* https://tc39.es/ecma262/#sec-year-number
* @param t
*/
export function YearFromTime(t) {
return new Date(t).getUTCFullYear();
return new Date(t).getUTCFullYear();
}
export function DaysInYear(y) {
if (y % 4 !== 0) {
return 365;
}
if (y % 100 !== 0) {
return 366;
}
if (y % 400 !== 0) {
return 365;
}
return 366;
if (y % 4 !== 0) {
return 365;
}
if (y % 100 !== 0) {
return 366;
}
if (y % 400 !== 0) {
return 365;
}
return 366;
}
export function DayWithinYear(t) {
return Day(t) - DayFromYear(YearFromTime(t));
return Day(t) - DayFromYear(YearFromTime(t));
}
export function InLeapYear(t) {
return DaysInYear(YearFromTime(t)) === 365 ? 0 : 1;
return DaysInYear(YearFromTime(t)) === 365 ? 0 : 1;
}
/**
* https://tc39.es/ecma262/#sec-month-number
* @param t
*/
* https://tc39.es/ecma262/#sec-month-number
* @param t
*/
export function MonthFromTime(t) {
var dwy = DayWithinYear(t);
var leap = InLeapYear(t);
if (dwy >= 0 && dwy < 31) {
return 0;
}
if (dwy < 59 + leap) {
return 1;
}
if (dwy < 90 + leap) {
return 2;
}
if (dwy < 120 + leap) {
return 3;
}
if (dwy < 151 + leap) {
return 4;
}
if (dwy < 181 + leap) {
return 5;
}
if (dwy < 212 + leap) {
return 6;
}
if (dwy < 243 + leap) {
return 7;
}
if (dwy < 273 + leap) {
return 8;
}
if (dwy < 304 + leap) {
return 9;
}
if (dwy < 334 + leap) {
return 10;
}
if (dwy < 365 + leap) {
return 11;
}
throw new Error('Invalid time');
const dwy = DayWithinYear(t);
const leap = InLeapYear(t);
if (dwy >= 0 && dwy < 31) {
return 0;
}
if (dwy < 59 + leap) {
return 1;
}
if (dwy < 90 + leap) {
return 2;
}
if (dwy < 120 + leap) {
return 3;
}
if (dwy < 151 + leap) {
return 4;
}
if (dwy < 181 + leap) {
return 5;
}
if (dwy < 212 + leap) {
return 6;
}
if (dwy < 243 + leap) {
return 7;
}
if (dwy < 273 + leap) {
return 8;
}
if (dwy < 304 + leap) {
return 9;
}
if (dwy < 334 + leap) {
return 10;
}
if (dwy < 365 + leap) {
return 11;
}
throw new Error("Invalid time");
}
export function DateFromTime(t) {
var dwy = DayWithinYear(t);
var mft = MonthFromTime(t);
var leap = InLeapYear(t);
if (mft === 0) {
return dwy + 1;
}
if (mft === 1) {
return dwy - 30;
}
if (mft === 2) {
return dwy - 58 - leap;
}
if (mft === 3) {
return dwy - 89 - leap;
}
if (mft === 4) {
return dwy - 119 - leap;
}
if (mft === 5) {
return dwy - 150 - leap;
}
if (mft === 6) {
return dwy - 180 - leap;
}
if (mft === 7) {
return dwy - 211 - leap;
}
if (mft === 8) {
return dwy - 242 - leap;
}
if (mft === 9) {
return dwy - 272 - leap;
}
if (mft === 10) {
return dwy - 303 - leap;
}
if (mft === 11) {
return dwy - 333 - leap;
}
throw new Error('Invalid time');
const dwy = DayWithinYear(t);
const mft = MonthFromTime(t);
const leap = InLeapYear(t);
if (mft === 0) {
return dwy + 1;
}
if (mft === 1) {
return dwy - 30;
}
if (mft === 2) {
return dwy - 58 - leap;
}
if (mft === 3) {
return dwy - 89 - leap;
}
if (mft === 4) {
return dwy - 119 - leap;
}
if (mft === 5) {
return dwy - 150 - leap;
}
if (mft === 6) {
return dwy - 180 - leap;
}
if (mft === 7) {
return dwy - 211 - leap;
}
if (mft === 8) {
return dwy - 242 - leap;
}
if (mft === 9) {
return dwy - 272 - leap;
}
if (mft === 10) {
return dwy - 303 - leap;
}
if (mft === 11) {
return dwy - 333 - leap;
}
throw new Error("Invalid time");
}
var HOURS_PER_DAY = 24;
var MINUTES_PER_HOUR = 60;
var SECONDS_PER_MINUTE = 60;
var MS_PER_SECOND = 1e3;
var MS_PER_MINUTE = MS_PER_SECOND * SECONDS_PER_MINUTE;
var MS_PER_HOUR = MS_PER_MINUTE * MINUTES_PER_HOUR;
const HOURS_PER_DAY = 24;
const MINUTES_PER_HOUR = 60;
const SECONDS_PER_MINUTE = 60;
const MS_PER_SECOND = 1e3;
const MS_PER_MINUTE = MS_PER_SECOND * SECONDS_PER_MINUTE;
const MS_PER_HOUR = MS_PER_MINUTE * MINUTES_PER_HOUR;
export function HourFromTime(t) {
return mod(Math.floor(t / MS_PER_HOUR), HOURS_PER_DAY);
return mod(Math.floor(t / MS_PER_HOUR), HOURS_PER_DAY);
}
export function MinFromTime(t) {
return mod(Math.floor(t / MS_PER_MINUTE), MINUTES_PER_HOUR);
return mod(Math.floor(t / MS_PER_MINUTE), MINUTES_PER_HOUR);
}
export function SecFromTime(t) {
return mod(Math.floor(t / MS_PER_SECOND), SECONDS_PER_MINUTE);
return mod(Math.floor(t / MS_PER_SECOND), SECONDS_PER_MINUTE);
}
function IsCallable(fn) {
return typeof fn === 'function';
return typeof fn === "function";
}
/**
* The abstract operation OrdinaryHasInstance implements
* the default algorithm for determining if an object O
* inherits from the instance object inheritance path
* provided by constructor C.
* @param C class
* @param O object
* @param internalSlots internalSlots
*/
* The abstract operation OrdinaryHasInstance implements
* the default algorithm for determining if an object O
* inherits from the instance object inheritance path
* provided by constructor C.
* @param C class
* @param O object
* @param internalSlots internalSlots
*/
export function OrdinaryHasInstance(C, O, internalSlots) {
if (!IsCallable(C)) {
return false;
}
if (internalSlots === null || internalSlots === void 0 ? void 0 : internalSlots.boundTargetFunction) {
var BC = internalSlots === null || internalSlots === void 0 ? void 0 : internalSlots.boundTargetFunction;
return O instanceof BC;
}
if (typeof O !== 'object') {
return false;
}
var P = C.prototype;
if (typeof P !== 'object') {
throw new TypeError('OrdinaryHasInstance called on an object with an invalid prototype property.');
}
return Object.prototype.isPrototypeOf.call(P, O);
if (!IsCallable(C)) {
return false;
}
if (internalSlots?.boundTargetFunction) {
let BC = internalSlots?.boundTargetFunction;
return O instanceof BC;
}
if (typeof O !== "object") {
return false;
}
let P = C.prototype;
if (typeof P !== "object") {
throw new TypeError("OrdinaryHasInstance called on an object with an invalid prototype property.");
}
return Object.prototype.isPrototypeOf.call(P, O);
}
export function msFromTime(t) {
return mod(t, MS_PER_SECOND);
return mod(t, MS_PER_SECOND);
}
function OrdinaryToPrimitive(O, hint) {
var methodNames;
if (hint === 'string') {
methodNames = ['toString', 'valueOf'];
}
else {
methodNames = ['valueOf', 'toString'];
}
for (var _i = 0, methodNames_1 = methodNames; _i < methodNames_1.length; _i++) {
var name_1 = methodNames_1[_i];
var method = O[name_1];
if (IsCallable(method)) {
var result = method.call(O);
if (typeof result !== 'object') {
return result;
}
}
}
throw new TypeError('Cannot convert object to primitive value');
let methodNames;
if (hint === "string") {
methodNames = ["toString", "valueOf"];
} else {
methodNames = ["valueOf", "toString"];
}
for (const name of methodNames) {
const method = O[name];
if (IsCallable(method)) {
let result = method.call(O);
if (typeof result !== "object") {
return result;
}
}
}
throw new TypeError("Cannot convert object to primitive value");
}
export function ToPrimitive(input, preferredType) {
if (typeof input === 'object' && input != null) {
var exoticToPrim = Symbol.toPrimitive in input ? input[Symbol.toPrimitive] : undefined;
var hint = void 0;
if (exoticToPrim !== undefined) {
if (preferredType === undefined) {
hint = 'default';
}
else if (preferredType === 'string') {
hint = 'string';
}
else {
invariant(preferredType === 'number', 'preferredType must be "string" or "number"');
hint = 'number';
}
var result = exoticToPrim.call(input, hint);
if (typeof result !== 'object') {
return result;
}
throw new TypeError('Cannot convert exotic object to primitive.');
}
if (preferredType === undefined) {
preferredType = 'number';
}
return OrdinaryToPrimitive(input, preferredType);
}
return input;
if (typeof input === "object" && input != null) {
const exoticToPrim = Symbol.toPrimitive in input ? input[Symbol.toPrimitive] : undefined;
let hint;
if (exoticToPrim !== undefined) {
if (preferredType === undefined) {
hint = "default";
} else if (preferredType === "string") {
hint = "string";
} else {
invariant(preferredType === "number", "preferredType must be \"string\" or \"number\"");
hint = "number";
}
let result = exoticToPrim.call(input, hint);
if (typeof result !== "object") {
return result;
}
throw new TypeError("Cannot convert exotic object to primitive.");
}
if (preferredType === undefined) {
preferredType = "number";
}
return OrdinaryToPrimitive(input, preferredType);
}
return input;
}
/**
* http://ecma-international.org/ecma-402/7.0/index.html#sec-canonicalizelocalelist
* @param locales
*/
* http://ecma-international.org/ecma-402/7.0/index.html#sec-canonicalizelocalelist
* @param locales
*/
export declare function CanonicalizeLocaleList(locales?: string | ReadonlyArray<string>): string[];
/**
* http://ecma-international.org/ecma-402/7.0/index.html#sec-canonicalizelocalelist
* @param locales
*/
* http://ecma-international.org/ecma-402/7.0/index.html#sec-canonicalizelocalelist
* @param locales
*/
export function CanonicalizeLocaleList(locales) {
// TODO
return Intl.getCanonicalLocales(locales);
// TODO
return Intl.getCanonicalLocales(locales);
}
/**
* CanonicalizeTimeZoneName ( timeZone )
* https://tc39.es/ecma402/#sec-canonicalizetimezonename
*
* Extended to support UTC offset time zones per ECMA-402 PR #788 (ES2026).
* Returns the canonical and case-regularized form of a timezone identifier.
*
* @param tz - The timezone identifier to canonicalize
* @param implDetails - Implementation details containing timezone data
* @returns The canonical timezone identifier
*/
export declare function CanonicalizeTimeZoneName(tz: string, { zoneNames, uppercaseLinks, }: {
zoneNames: readonly string[];
uppercaseLinks: Record<string, string>;
* CanonicalizeTimeZoneName ( timeZone )
* https://tc39.es/ecma402/#sec-canonicalizetimezonename
*
* Extended to support UTC offset time zones per ECMA-402 PR #788 (ES2026).
* Returns the canonical and case-regularized form of a timezone identifier.
*
* @param tz - The timezone identifier to canonicalize
* @param implDetails - Implementation details containing timezone data
* @returns The canonical timezone identifier
*/
export declare function CanonicalizeTimeZoneName(tz: string, { zoneNames, uppercaseLinks }: {
zoneNames: readonly string[];
uppercaseLinks: Record<string, string>;
}): string;
// Cached regex patterns for performance
var OFFSET_TIMEZONE_PREFIX_REGEX = /^[+-]/;
var OFFSET_TIMEZONE_FORMAT_REGEX = /^([+-])(\d{2})(?::?(\d{2}))?(?::?(\d{2}))?(?:\.(\d{1,9}))?$/;
var TRAILING_ZEROS_REGEX = /0+$/;
const OFFSET_TIMEZONE_PREFIX_REGEX = /^[+-]/;
const OFFSET_TIMEZONE_FORMAT_REGEX = /^([+-])(\d{2})(?::?(\d{2}))?(?::?(\d{2}))?(?:\.(\d{1,9}))?$/;
const TRAILING_ZEROS_REGEX = /0+$/;
/**
* IsTimeZoneOffsetString ( offsetString )
* https://tc39.es/ecma262/#sec-istimezoneoffsetstring
*
* Simplified check to determine if a string is a UTC offset identifier.
*
* @param offsetString - The string to check
* @returns true if offsetString starts with '+' or '-'
*/
* IsTimeZoneOffsetString ( offsetString )
* https://tc39.es/ecma262/#sec-istimezoneoffsetstring
*
* Simplified check to determine if a string is a UTC offset identifier.
*
* @param offsetString - The string to check
* @returns true if offsetString starts with '+' or '-'
*/
function IsTimeZoneOffsetString(offsetString) {
// 1. If offsetString does not start with '+' or '-', return false
return OFFSET_TIMEZONE_PREFIX_REGEX.test(offsetString);
// 1. If offsetString does not start with '+' or '-', return false
return OFFSET_TIMEZONE_PREFIX_REGEX.test(offsetString);
}
/**
* ParseTimeZoneOffsetString ( offsetString )
* https://tc39.es/ecma262/#sec-parsetimezoneoffsetstring
*
* Parses a UTC offset string and returns its canonical representation.
* Normalizes various formats (±HH, ±HHMM, ±HH:MM, etc.) to ±HH:MM format.
*
* @param offsetString - The UTC offset string to parse
* @returns The canonical offset string in ±HH:MM format (with :SS.sss if non-zero)
*/
* ParseTimeZoneOffsetString ( offsetString )
* https://tc39.es/ecma262/#sec-parsetimezoneoffsetstring
*
* Parses a UTC offset string and returns its canonical representation.
* Normalizes various formats (±HH, ±HHMM, ±HH:MM, etc.) to ±HH:MM format.
*
* @param offsetString - The UTC offset string to parse
* @returns The canonical offset string in ±HH:MM format (with :SS.sss if non-zero)
*/
function ParseTimeZoneOffsetString(offsetString) {
// 1. Let parseResult be ParseText(offsetString, UTCOffset)
var match = OFFSET_TIMEZONE_FORMAT_REGEX.exec(offsetString);
// 2. Assert: parseResult is not a List of errors (validated by IsValidTimeZoneName)
if (!match) {
return offsetString;
}
// 3. Extract components from parseResult
var sign = match[1];
var hours = match[2];
var minutes = match[3] ? match[3] : '00';
var seconds = match[4];
var fractional = match[5];
// 4. Build canonical format: ±HH:MM
var canonical = "".concat(sign).concat(hours, ":").concat(minutes);
// 5. If seconds are present and non-zero (or fractional present), include them
if (seconds && (parseInt(seconds, 10) !== 0 || fractional)) {
canonical += ":".concat(seconds);
// 6. If fractional seconds present, include them (trim trailing zeros)
if (fractional) {
var trimmedFractional = fractional.replace(TRAILING_ZEROS_REGEX, '');
if (trimmedFractional) {
canonical += ".".concat(trimmedFractional);
}
}
}
// 7. Return canonical representation
return canonical;
// 1. Let parseResult be ParseText(offsetString, UTCOffset)
const match = OFFSET_TIMEZONE_FORMAT_REGEX.exec(offsetString);
// 2. Assert: parseResult is not a List of errors (validated by IsValidTimeZoneName)
if (!match) {
return offsetString;
}
// 3. Extract components from parseResult
const sign = match[1];
const hours = match[2];
const minutes = match[3] ? match[3] : "00";
const seconds = match[4];
const fractional = match[5];
// 4. Build canonical format: ±HH:MM
let canonical = `${sign}${hours}:${minutes}`;
// 5. If seconds are present and non-zero (or fractional present), include them
if (seconds && (parseInt(seconds, 10) !== 0 || fractional)) {
canonical += `:${seconds}`;
// 6. If fractional seconds present, include them (trim trailing zeros)
if (fractional) {
const trimmedFractional = fractional.replace(TRAILING_ZEROS_REGEX, "");
if (trimmedFractional) {
canonical += `.${trimmedFractional}`;
}
}
}
// 7. Return canonical representation
return canonical;
}
/**
* CanonicalizeTimeZoneName ( timeZone )
* https://tc39.es/ecma402/#sec-canonicalizetimezonename
*
* Extended to support UTC offset time zones per ECMA-402 PR #788 (ES2026).
* Returns the canonical and case-regularized form of a timezone identifier.
*
* @param tz - The timezone identifier to canonicalize
* @param implDetails - Implementation details containing timezone data
* @returns The canonical timezone identifier
*/
export function CanonicalizeTimeZoneName(tz, _a) {
var zoneNames = _a.zoneNames, uppercaseLinks = _a.uppercaseLinks;
// 1. If IsTimeZoneOffsetString(timeZone) is true, then
// a. Return ParseTimeZoneOffsetString(timeZone)
// Per ECMA-402 PR #788, UTC offset identifiers are canonicalized
if (IsTimeZoneOffsetString(tz)) {
return ParseTimeZoneOffsetString(tz);
}
// 2. Let ianaTimeZone be the String value of the Zone or Link name
// in the IANA Time Zone Database that is an ASCII-case-insensitive
// match of timeZone
var uppercasedTz = tz.toUpperCase();
var uppercasedZones = zoneNames.reduce(function (all, z) {
all[z.toUpperCase()] = z;
return all;
}, {});
var ianaTimeZone = uppercaseLinks[uppercasedTz] || uppercasedZones[uppercasedTz];
// 3. If ianaTimeZone is "Etc/UTC" or "Etc/GMT", return "UTC"
if (ianaTimeZone === 'Etc/UTC' || ianaTimeZone === 'Etc/GMT') {
return 'UTC';
}
// 4. Return ianaTimeZone
return ianaTimeZone;
* CanonicalizeTimeZoneName ( timeZone )
* https://tc39.es/ecma402/#sec-canonicalizetimezonename
*
* Extended to support UTC offset time zones per ECMA-402 PR #788 (ES2026).
* Returns the canonical and case-regularized form of a timezone identifier.
*
* @param tz - The timezone identifier to canonicalize
* @param implDetails - Implementation details containing timezone data
* @returns The canonical timezone identifier
*/
export function CanonicalizeTimeZoneName(tz, { zoneNames, uppercaseLinks }) {
// 1. If IsTimeZoneOffsetString(timeZone) is true, then
// a. Return ParseTimeZoneOffsetString(timeZone)
// Per ECMA-402 PR #788, UTC offset identifiers are canonicalized
if (IsTimeZoneOffsetString(tz)) {
return ParseTimeZoneOffsetString(tz);
}
// 2. Let ianaTimeZone be the String value of the Zone or Link name
// in the IANA Time Zone Database that is an ASCII-case-insensitive
// match of timeZone
const uppercasedTz = tz.toUpperCase();
const uppercasedZones = zoneNames.reduce((all, z) => {
all[z.toUpperCase()] = z;
return all;
}, {});
const ianaTimeZone = uppercaseLinks[uppercasedTz] || uppercasedZones[uppercasedTz];
// 3. If ianaTimeZone is "Etc/UTC" or "Etc/GMT", return "UTC"
if (ianaTimeZone === "Etc/UTC" || ianaTimeZone === "Etc/GMT") {
return "UTC";
}
// 4. Return ianaTimeZone
return ianaTimeZone;
}
/**
* https://tc39.es/ecma402/#sec-coerceoptionstoobject
* @param options
* @returns
*/
* https://tc39.es/ecma402/#sec-coerceoptionstoobject
* @param options
* @returns
*/
export declare function CoerceOptionsToObject<T>(options?: T): T;

@@ -1,12 +0,12 @@

import { ToObject } from './262.js';
import { ToObject } from "./262.js";
/**
* https://tc39.es/ecma402/#sec-coerceoptionstoobject
* @param options
* @returns
*/
* https://tc39.es/ecma402/#sec-coerceoptionstoobject
* @param options
* @returns
*/
export function CoerceOptionsToObject(options) {
if (typeof options === 'undefined') {
return Object.create(null);
}
return ToObject(options);
if (typeof options === "undefined") {
return Object.create(null);
}
return ToObject(options);
}

@@ -1,4 +0,4 @@

import { Decimal } from 'decimal.js';
import { Decimal } from "decimal.js";
export declare const TEN: Decimal;
export declare const ZERO: Decimal;
export declare const NEGATIVE_ZERO: Decimal;

@@ -1,4 +0,4 @@

import { Decimal } from 'decimal.js';
export var TEN = new Decimal(10);
export var ZERO = new Decimal(0);
export var NEGATIVE_ZERO = new Decimal(-0);
import { Decimal } from "decimal.js";
export const TEN = new Decimal(10);
export const ZERO = new Decimal(0);
export const NEGATIVE_ZERO = new Decimal(-0);
declare class MissingLocaleDataError extends Error {
type: string;
type: string;
}
export declare function isMissingLocaleDataError(e: Error): e is MissingLocaleDataError;
export {};
+4
-11

@@ -1,13 +0,6 @@

import { __extends } from "tslib";
var MissingLocaleDataError = /** @class */ (function (_super) {
__extends(MissingLocaleDataError, _super);
function MissingLocaleDataError() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.type = 'MISSING_LOCALE_DATA';
return _this;
}
return MissingLocaleDataError;
}(Error));
class MissingLocaleDataError extends Error {
type = "MISSING_LOCALE_DATA";
}
export function isMissingLocaleDataError(e) {
return e.type === 'MISSING_LOCALE_DATA';
return e.type === "MISSING_LOCALE_DATA";
}
/**
* https://tc39.es/ecma402/#sec-defaultnumberoption
* @param val
* @param min
* @param max
* @param fallback
*/
* https://tc39.es/ecma402/#sec-defaultnumberoption
* @param val
* @param min
* @param max
* @param fallback
*/
export declare function DefaultNumberOption<F extends number | undefined>(inputVal: unknown, min: number, max: number, fallback: F): F extends number ? number : number | undefined;
/**
* https://tc39.es/ecma402/#sec-defaultnumberoption
* @param val
* @param min
* @param max
* @param fallback
*/
* https://tc39.es/ecma402/#sec-defaultnumberoption
* @param val
* @param min
* @param max
* @param fallback
*/
export function DefaultNumberOption(inputVal, min, max, fallback) {
if (inputVal === undefined) {
// @ts-expect-error
return fallback;
}
var val = Number(inputVal);
if (isNaN(val) || val < min || val > max) {
throw new RangeError("".concat(val, " is outside of range [").concat(min, ", ").concat(max, "]"));
}
return Math.floor(val);
if (inputVal === undefined) {
// @ts-expect-error
return fallback;
}
const val = Number(inputVal);
if (isNaN(val) || val < min || val > max) {
throw new RangeError(`${val} is outside of range [${min}, ${max}]`);
}
return Math.floor(val);
}

@@ -1,9 +0,5 @@

/**
* https://tc39.es/ecma402/#sec-getnumberoption
* @param options
* @param property
* @param min
* @param max
* @param fallback
*/
export declare function GetNumberOption<T extends object, K extends keyof T, F extends number | undefined>(options: T, property: K, minimum: number, maximum: number, fallback: F): F extends number ? number : number | undefined;
export declare function GetNumberOption<
T extends object,
K extends keyof T,
F extends number | undefined
>(options: T, property: K, minimum: number, maximum: number, fallback: F): F extends number ? number : number | undefined;
/**
* https://tc39.es/ecma402/#sec-getnumberoption
* @param options
* @param property
* @param min
* @param max
* @param fallback
*/
import { DefaultNumberOption } from './DefaultNumberOption.js';
* https://tc39.es/ecma402/#sec-getnumberoption
* @param options
* @param property
* @param min
* @param max
* @param fallback
*/
import { DefaultNumberOption } from "./DefaultNumberOption.js";
export function GetNumberOption(options, property, minimum, maximum, fallback) {
var val = options[property];
return DefaultNumberOption(val, minimum, maximum, fallback);
const val = options[property];
return DefaultNumberOption(val, minimum, maximum, fallback);
}
/**
* https://tc39.es/ecma402/#sec-getoption
* @param opts
* @param prop
* @param type
* @param values
* @param fallback
*/
export declare function GetOption<T extends object, K extends keyof T, F>(opts: T, prop: K, type: 'string' | 'boolean', values: readonly T[K][] | undefined, fallback: F): Exclude<T[K], undefined> | F;
* https://tc39.es/ecma402/#sec-getoption
* @param opts
* @param prop
* @param type
* @param values
* @param fallback
*/
export declare function GetOption<
T extends object,
K extends keyof T,
F
>(opts: T, prop: K, type: "string" | "boolean", values: readonly T[K][] | undefined, fallback: F): Exclude<T[K], undefined> | F;

@@ -1,31 +0,31 @@

import { ToString } from './262.js';
import { ToString } from "./262.js";
/**
* https://tc39.es/ecma402/#sec-getoption
* @param opts
* @param prop
* @param type
* @param values
* @param fallback
*/
* https://tc39.es/ecma402/#sec-getoption
* @param opts
* @param prop
* @param type
* @param values
* @param fallback
*/
export function GetOption(opts, prop, type, values, fallback) {
if (typeof opts !== 'object') {
throw new TypeError('Options must be an object');
}
var value = opts[prop];
if (value !== undefined) {
if (type !== 'boolean' && type !== 'string') {
throw new TypeError('invalid type');
}
if (type === 'boolean') {
value = Boolean(value);
}
if (type === 'string') {
value = ToString(value);
}
if (values !== undefined && !values.filter(function (val) { return val == value; }).length) {
throw new RangeError("".concat(value, " is not within ").concat(values.join(', ')));
}
return value;
}
return fallback;
if (typeof opts !== "object") {
throw new TypeError("Options must be an object");
}
let value = opts[prop];
if (value !== undefined) {
if (type !== "boolean" && type !== "string") {
throw new TypeError("invalid type");
}
if (type === "boolean") {
value = Boolean(value);
}
if (type === "string") {
value = ToString(value);
}
if (values !== undefined && !values.filter((val) => val == value).length) {
throw new RangeError(`${value} is not within ${values.join(", ")}`);
}
return value;
}
return fallback;
}
/**
* https://tc39.es/ecma402/#sec-getoptionsobject
* @param options
* @returns
*/
* https://tc39.es/ecma402/#sec-getoptionsobject
* @param options
* @returns
*/
export declare function GetOptionsObject<T extends object>(options?: T): T;
/**
* https://tc39.es/ecma402/#sec-getoptionsobject
* @param options
* @returns
*/
* https://tc39.es/ecma402/#sec-getoptionsobject
* @param options
* @returns
*/
export function GetOptionsObject(options) {
if (typeof options === 'undefined') {
return Object.create(null);
}
if (typeof options === 'object') {
return options;
}
throw new TypeError('Options must be an object');
if (typeof options === "undefined") {
return Object.create(null);
}
if (typeof options === "object") {
return options;
}
throw new TypeError("Options must be an object");
}

@@ -1,10 +0,4 @@

/**
* https://tc39.es/ecma402/#sec-getstringorbooleanoption
* @param opts
* @param prop
* @param values
* @param trueValue
* @param falsyValue
* @param fallback
*/
export declare function GetStringOrBooleanOption<T extends object, K extends keyof T>(opts: T, prop: K, values: T[K][] | undefined, trueValue: T[K] | boolean, falsyValue: T[K] | boolean, fallback: T[K] | boolean): T[K] | boolean;
export declare function GetStringOrBooleanOption<
T extends object,
K extends keyof T
>(opts: T, prop: K, values: T[K][] | undefined, trueValue: T[K] | boolean, falsyValue: T[K] | boolean, fallback: T[K] | boolean): T[K] | boolean;
/**
* https://tc39.es/ecma402/#sec-getstringorbooleanoption
* @param opts
* @param prop
* @param values
* @param trueValue
* @param falsyValue
* @param fallback
*/
import { ToString } from './262.js';
* https://tc39.es/ecma402/#sec-getstringorbooleanoption
* @param opts
* @param prop
* @param values
* @param trueValue
* @param falsyValue
* @param fallback
*/
import { ToString } from "./262.js";
export function GetStringOrBooleanOption(opts, prop, values, trueValue, falsyValue, fallback) {
var value = opts[prop];
if (value === undefined) {
return fallback;
}
if (value === true) {
return trueValue;
}
var valueBoolean = Boolean(value);
if (valueBoolean === false) {
return falsyValue;
}
value = ToString(value);
if (value === 'true' || value === 'false') {
return fallback;
}
if ((values || []).indexOf(value) === -1) {
throw new RangeError("Invalid value ".concat(value));
}
return value;
let value = opts[prop];
if (value === undefined) {
return fallback;
}
if (value === true) {
return trueValue;
}
const valueBoolean = Boolean(value);
if (valueBoolean === false) {
return falsyValue;
}
value = ToString(value);
if (value === "true" || value === "false") {
return fallback;
}
if ((values || []).indexOf(value) === -1) {
throw new RangeError(`Invalid value ${value}`);
}
return value;
}

@@ -1,47 +0,47 @@

export * from './CanonicalizeLocaleList.js';
export * from './CanonicalizeTimeZoneName.js';
export * from './CoerceOptionsToObject.js';
export * from './GetNumberOption.js';
export * from './GetOption.js';
export * from './GetOptionsObject.js';
export * from './GetStringOrBooleanOption.js';
export * from './IsSanctionedSimpleUnitIdentifier.js';
export * from './IsValidTimeZoneName.js';
export * from './IsWellFormedCurrencyCode.js';
export * from './IsWellFormedUnitIdentifier.js';
export * from './NumberFormat/ApplyUnsignedRoundingMode.js';
export * from './NumberFormat/CollapseNumberRange.js';
export * from './NumberFormat/ComputeExponent.js';
export * from './NumberFormat/ComputeExponentForMagnitude.js';
export * from './NumberFormat/CurrencyDigits.js';
export { default as _formatToParts } from './NumberFormat/format_to_parts.js';
export * from './NumberFormat/FormatApproximately.js';
export * from './NumberFormat/FormatNumeric.js';
export * from './NumberFormat/FormatNumericRange.js';
export * from './NumberFormat/FormatNumericRangeToParts.js';
export * from './NumberFormat/FormatNumericToParts.js';
export * from './NumberFormat/FormatNumericToString.js';
export * from './NumberFormat/GetUnsignedRoundingMode.js';
export * from './NumberFormat/InitializeNumberFormat.js';
export * from './NumberFormat/PartitionNumberPattern.js';
export * from './NumberFormat/PartitionNumberRangePattern.js';
export * from './NumberFormat/SetNumberFormatDigitOptions.js';
export * from './NumberFormat/SetNumberFormatUnitOptions.js';
export * from './NumberFormat/ToRawFixed.js';
export * from './NumberFormat/ToRawPrecision.js';
export * from './PartitionPattern.js';
export * from './SupportedLocales.js';
export { createDataProperty, defineProperty, getInternalSlot, getMultiInternalSlots, isLiteralPart, setInternalSlot, setMultiInternalSlots, } from './utils.js';
export type { LiteralPart } from './utils.js';
export * from './262.js';
export { isMissingLocaleDataError } from './data.js';
export type { LocaleData } from './types/core.js';
export * from './types/date-time.js';
export * from './types/displaynames.js';
export * from './types/list.js';
export * from './types/number.js';
export * from './types/plural-rules.js';
export * from './types/relative-time.js';
export { createMemoizedDateTimeFormat, createMemoizedListFormat, createMemoizedLocale, createMemoizedNumberFormat, createMemoizedPluralRules, invariant, } from './utils.js';
export { ZERO } from './constants.js';
export { ToIntlMathematicalValue } from './ToIntlMathematicalValue.js';
export * from "./CanonicalizeLocaleList.js";
export * from "./CanonicalizeTimeZoneName.js";
export * from "./CoerceOptionsToObject.js";
export * from "./GetNumberOption.js";
export * from "./GetOption.js";
export * from "./GetOptionsObject.js";
export * from "./GetStringOrBooleanOption.js";
export * from "./IsSanctionedSimpleUnitIdentifier.js";
export * from "./IsValidTimeZoneName.js";
export * from "./IsWellFormedCurrencyCode.js";
export * from "./IsWellFormedUnitIdentifier.js";
export * from "./NumberFormat/ApplyUnsignedRoundingMode.js";
export * from "./NumberFormat/CollapseNumberRange.js";
export * from "./NumberFormat/ComputeExponent.js";
export * from "./NumberFormat/ComputeExponentForMagnitude.js";
export * from "./NumberFormat/CurrencyDigits.js";
export { default as _formatToParts } from "./NumberFormat/format_to_parts.js";
export * from "./NumberFormat/FormatApproximately.js";
export * from "./NumberFormat/FormatNumeric.js";
export * from "./NumberFormat/FormatNumericRange.js";
export * from "./NumberFormat/FormatNumericRangeToParts.js";
export * from "./NumberFormat/FormatNumericToParts.js";
export * from "./NumberFormat/FormatNumericToString.js";
export * from "./NumberFormat/GetUnsignedRoundingMode.js";
export * from "./NumberFormat/InitializeNumberFormat.js";
export * from "./NumberFormat/PartitionNumberPattern.js";
export * from "./NumberFormat/PartitionNumberRangePattern.js";
export * from "./NumberFormat/SetNumberFormatDigitOptions.js";
export * from "./NumberFormat/SetNumberFormatUnitOptions.js";
export * from "./NumberFormat/ToRawFixed.js";
export * from "./NumberFormat/ToRawPrecision.js";
export * from "./PartitionPattern.js";
export * from "./SupportedLocales.js";
export { createDataProperty, defineProperty, getInternalSlot, getMultiInternalSlots, isLiteralPart, setInternalSlot, setMultiInternalSlots } from "./utils.js";
export type { LiteralPart } from "./utils.js";
export * from "./262.js";
export { isMissingLocaleDataError } from "./data.js";
export type { LocaleData } from "./types/core.js";
export * from "./types/date-time.js";
export * from "./types/displaynames.js";
export * from "./types/list.js";
export * from "./types/number.js";
export * from "./types/plural-rules.js";
export * from "./types/relative-time.js";
export { createMemoizedDateTimeFormat, createMemoizedListFormat, createMemoizedLocale, createMemoizedNumberFormat, createMemoizedPluralRules, invariant } from "./utils.js";
export { ZERO } from "./constants.js";
export { ToIntlMathematicalValue } from "./ToIntlMathematicalValue.js";
+45
-45

@@ -1,45 +0,45 @@

export * from './CanonicalizeLocaleList.js';
export * from './CanonicalizeTimeZoneName.js';
export * from './CoerceOptionsToObject.js';
export * from './GetNumberOption.js';
export * from './GetOption.js';
export * from './GetOptionsObject.js';
export * from './GetStringOrBooleanOption.js';
export * from './IsSanctionedSimpleUnitIdentifier.js';
export * from './IsValidTimeZoneName.js';
export * from './IsWellFormedCurrencyCode.js';
export * from './IsWellFormedUnitIdentifier.js';
export * from './NumberFormat/ApplyUnsignedRoundingMode.js';
export * from './NumberFormat/CollapseNumberRange.js';
export * from './NumberFormat/ComputeExponent.js';
export * from './NumberFormat/ComputeExponentForMagnitude.js';
export * from './NumberFormat/CurrencyDigits.js';
export { default as _formatToParts } from './NumberFormat/format_to_parts.js';
export * from './NumberFormat/FormatApproximately.js';
export * from './NumberFormat/FormatNumeric.js';
export * from './NumberFormat/FormatNumericRange.js';
export * from './NumberFormat/FormatNumericRangeToParts.js';
export * from './NumberFormat/FormatNumericToParts.js';
export * from './NumberFormat/FormatNumericToString.js';
export * from './NumberFormat/GetUnsignedRoundingMode.js';
export * from './NumberFormat/InitializeNumberFormat.js';
export * from './NumberFormat/PartitionNumberPattern.js';
export * from './NumberFormat/PartitionNumberRangePattern.js';
export * from './NumberFormat/SetNumberFormatDigitOptions.js';
export * from './NumberFormat/SetNumberFormatUnitOptions.js';
export * from './NumberFormat/ToRawFixed.js';
export * from './NumberFormat/ToRawPrecision.js';
export * from './PartitionPattern.js';
export * from './SupportedLocales.js';
export { createDataProperty, defineProperty, getInternalSlot, getMultiInternalSlots, isLiteralPart, setInternalSlot, setMultiInternalSlots, } from './utils.js';
export * from './262.js';
export { isMissingLocaleDataError } from './data.js';
export * from './types/date-time.js';
export * from './types/displaynames.js';
export * from './types/list.js';
export * from './types/number.js';
export * from './types/plural-rules.js';
export * from './types/relative-time.js';
export { createMemoizedDateTimeFormat, createMemoizedListFormat, createMemoizedLocale, createMemoizedNumberFormat, createMemoizedPluralRules, invariant, } from './utils.js';
export { ZERO } from './constants.js';
export { ToIntlMathematicalValue } from './ToIntlMathematicalValue.js';
export * from "./CanonicalizeLocaleList.js";
export * from "./CanonicalizeTimeZoneName.js";
export * from "./CoerceOptionsToObject.js";
export * from "./GetNumberOption.js";
export * from "./GetOption.js";
export * from "./GetOptionsObject.js";
export * from "./GetStringOrBooleanOption.js";
export * from "./IsSanctionedSimpleUnitIdentifier.js";
export * from "./IsValidTimeZoneName.js";
export * from "./IsWellFormedCurrencyCode.js";
export * from "./IsWellFormedUnitIdentifier.js";
export * from "./NumberFormat/ApplyUnsignedRoundingMode.js";
export * from "./NumberFormat/CollapseNumberRange.js";
export * from "./NumberFormat/ComputeExponent.js";
export * from "./NumberFormat/ComputeExponentForMagnitude.js";
export * from "./NumberFormat/CurrencyDigits.js";
export { default as _formatToParts } from "./NumberFormat/format_to_parts.js";
export * from "./NumberFormat/FormatApproximately.js";
export * from "./NumberFormat/FormatNumeric.js";
export * from "./NumberFormat/FormatNumericRange.js";
export * from "./NumberFormat/FormatNumericRangeToParts.js";
export * from "./NumberFormat/FormatNumericToParts.js";
export * from "./NumberFormat/FormatNumericToString.js";
export * from "./NumberFormat/GetUnsignedRoundingMode.js";
export * from "./NumberFormat/InitializeNumberFormat.js";
export * from "./NumberFormat/PartitionNumberPattern.js";
export * from "./NumberFormat/PartitionNumberRangePattern.js";
export * from "./NumberFormat/SetNumberFormatDigitOptions.js";
export * from "./NumberFormat/SetNumberFormatUnitOptions.js";
export * from "./NumberFormat/ToRawFixed.js";
export * from "./NumberFormat/ToRawPrecision.js";
export * from "./PartitionPattern.js";
export * from "./SupportedLocales.js";
export { createDataProperty, defineProperty, getInternalSlot, getMultiInternalSlots, isLiteralPart, setInternalSlot, setMultiInternalSlots } from "./utils.js";
export * from "./262.js";
export { isMissingLocaleDataError } from "./data.js";
export * from "./types/date-time.js";
export * from "./types/displaynames.js";
export * from "./types/list.js";
export * from "./types/number.js";
export * from "./types/plural-rules.js";
export * from "./types/relative-time.js";
export { createMemoizedDateTimeFormat, createMemoizedListFormat, createMemoizedLocale, createMemoizedNumberFormat, createMemoizedPluralRules, invariant } from "./utils.js";
export { ZERO } from "./constants.js";
export { ToIntlMathematicalValue } from "./ToIntlMathematicalValue.js";
/**
* https://tc39.es/ecma402/#table-sanctioned-simple-unit-identifiers
*/
* https://tc39.es/ecma402/#table-sanctioned-simple-unit-identifiers
*/
export declare const SANCTIONED_UNITS: readonly ["angle-degree", "area-acre", "area-hectare", "concentr-percent", "digital-bit", "digital-byte", "digital-gigabit", "digital-gigabyte", "digital-kilobit", "digital-kilobyte", "digital-megabit", "digital-megabyte", "digital-petabyte", "digital-terabit", "digital-terabyte", "duration-day", "duration-hour", "duration-millisecond", "duration-minute", "duration-month", "duration-second", "duration-week", "duration-year", "length-centimeter", "length-foot", "length-inch", "length-kilometer", "length-meter", "length-mile-scandinavian", "length-mile", "length-millimeter", "length-yard", "mass-gram", "mass-kilogram", "mass-ounce", "mass-pound", "mass-stone", "temperature-celsius", "temperature-fahrenheit", "volume-fluid-ounce", "volume-gallon", "volume-liter", "volume-milliliter"];
// In CLDR, the unit name always follows the form `namespace-unit` pattern.
// For example: `digital-bit` instead of `bit`. This function removes the namespace prefix.
export declare function removeUnitNamespace(unit: string): string;
/**
* https://tc39.es/ecma402/#table-sanctioned-simple-unit-identifiers
*/
* https://tc39.es/ecma402/#table-sanctioned-simple-unit-identifiers
*/
export declare const SIMPLE_UNITS: string[];
/**
* https://tc39.es/ecma402/#sec-issanctionedsimpleunitidentifier
*/
* https://tc39.es/ecma402/#sec-issanctionedsimpleunitidentifier
*/
export declare function IsSanctionedSimpleUnitIdentifier(unitIdentifier: string): boolean;
/**
* https://tc39.es/ecma402/#table-sanctioned-simple-unit-identifiers
*/
export var SANCTIONED_UNITS = [
'angle-degree',
'area-acre',
'area-hectare',
'concentr-percent',
'digital-bit',
'digital-byte',
'digital-gigabit',
'digital-gigabyte',
'digital-kilobit',
'digital-kilobyte',
'digital-megabit',
'digital-megabyte',
'digital-petabyte',
'digital-terabit',
'digital-terabyte',
'duration-day',
'duration-hour',
'duration-millisecond',
'duration-minute',
'duration-month',
'duration-second',
'duration-week',
'duration-year',
'length-centimeter',
'length-foot',
'length-inch',
'length-kilometer',
'length-meter',
'length-mile-scandinavian',
'length-mile',
'length-millimeter',
'length-yard',
'mass-gram',
'mass-kilogram',
'mass-ounce',
'mass-pound',
'mass-stone',
'temperature-celsius',
'temperature-fahrenheit',
'volume-fluid-ounce',
'volume-gallon',
'volume-liter',
'volume-milliliter',
* https://tc39.es/ecma402/#table-sanctioned-simple-unit-identifiers
*/
export const SANCTIONED_UNITS = [
"angle-degree",
"area-acre",
"area-hectare",
"concentr-percent",
"digital-bit",
"digital-byte",
"digital-gigabit",
"digital-gigabyte",
"digital-kilobit",
"digital-kilobyte",
"digital-megabit",
"digital-megabyte",
"digital-petabyte",
"digital-terabit",
"digital-terabyte",
"duration-day",
"duration-hour",
"duration-millisecond",
"duration-minute",
"duration-month",
"duration-second",
"duration-week",
"duration-year",
"length-centimeter",
"length-foot",
"length-inch",
"length-kilometer",
"length-meter",
"length-mile-scandinavian",
"length-mile",
"length-millimeter",
"length-yard",
"mass-gram",
"mass-kilogram",
"mass-ounce",
"mass-pound",
"mass-stone",
"temperature-celsius",
"temperature-fahrenheit",
"volume-fluid-ounce",
"volume-gallon",
"volume-liter",
"volume-milliliter"
];

@@ -52,13 +52,13 @@ // In CLDR, the unit name always follows the form `namespace-unit` pattern.

export function removeUnitNamespace(unit) {
return unit.slice(unit.indexOf('-') + 1);
return unit.slice(unit.indexOf("-") + 1);
}
/**
* https://tc39.es/ecma402/#table-sanctioned-simple-unit-identifiers
*/
export var SIMPLE_UNITS = SANCTIONED_UNITS.map(removeUnitNamespace);
* https://tc39.es/ecma402/#table-sanctioned-simple-unit-identifiers
*/
export const SIMPLE_UNITS = SANCTIONED_UNITS.map(removeUnitNamespace);
/**
* https://tc39.es/ecma402/#sec-issanctionedsimpleunitidentifier
*/
* https://tc39.es/ecma402/#sec-issanctionedsimpleunitidentifier
*/
export function IsSanctionedSimpleUnitIdentifier(unitIdentifier) {
return SIMPLE_UNITS.indexOf(unitIdentifier) > -1;
return SIMPLE_UNITS.indexOf(unitIdentifier) > -1;
}
/**
* IsValidTimeZoneName ( timeZone )
* https://tc39.es/ecma402/#sec-isvalidtimezonename
*
* Extended to support UTC offset time zones per ECMA-402 PR #788 (ES2026).
* The abstract operation validates both:
* 1. UTC offset identifiers (e.g., "+01:00", "-05:30")
* 2. Available named time zone identifiers from IANA Time Zone Database
*
* @param tz - The timezone identifier to validate
* @param implDetails - Implementation details containing timezone data
* @returns true if timeZone is a valid identifier
*/
export declare function IsValidTimeZoneName(tz: string, { zoneNamesFromData, uppercaseLinks, }: {
zoneNamesFromData: readonly string[];
uppercaseLinks: Record<string, string>;
* IsValidTimeZoneName ( timeZone )
* https://tc39.es/ecma402/#sec-isvalidtimezonename
*
* Extended to support UTC offset time zones per ECMA-402 PR #788 (ES2026).
* The abstract operation validates both:
* 1. UTC offset identifiers (e.g., "+01:00", "-05:30")
* 2. Available named time zone identifiers from IANA Time Zone Database
*
* @param tz - The timezone identifier to validate
* @param implDetails - Implementation details containing timezone data
* @returns true if timeZone is a valid identifier
*/
export declare function IsValidTimeZoneName(tz: string, { zoneNamesFromData, uppercaseLinks }: {
zoneNamesFromData: readonly string[];
uppercaseLinks: Record<string, string>;
}): boolean;
// Cached regex patterns for performance
var OFFSET_TIMEZONE_PREFIX_REGEX = /^[+-]/;
var OFFSET_TIMEZONE_FORMAT_REGEX = /^([+-])(\d{2})(?::?(\d{2}))?(?::?(\d{2}))?(?:\.(\d{1,9}))?$/;
const OFFSET_TIMEZONE_PREFIX_REGEX = /^[+-]/;
const OFFSET_TIMEZONE_FORMAT_REGEX = /^([+-])(\d{2})(?::?(\d{2}))?(?::?(\d{2}))?(?:\.(\d{1,9}))?$/;
/**
* IsTimeZoneOffsetString ( offsetString )
* https://tc39.es/ecma262/#sec-istimezoneoffsetstring
*
* Validates whether a string represents a valid UTC offset timezone.
* Supports formats: ±HH, ±HHMM, ±HH:MM, ±HH:MM:SS, ±HH:MM:SS.sss
*
* @param offsetString - The string to validate as a timezone offset
* @returns true if offsetString is a valid UTC offset format
*/
* IsTimeZoneOffsetString ( offsetString )
* https://tc39.es/ecma262/#sec-istimezoneoffsetstring
*
* Validates whether a string represents a valid UTC offset timezone.
* Supports formats: ±HH, ±HHMM, ±HH:MM, ±HH:MM:SS, ±HH:MM:SS.sss
*
* @param offsetString - The string to validate as a timezone offset
* @returns true if offsetString is a valid UTC offset format
*/
function IsTimeZoneOffsetString(offsetString) {
// 1. If offsetString does not start with '+' or '-', return false
if (!OFFSET_TIMEZONE_PREFIX_REGEX.test(offsetString)) {
return false;
}
// 2. Let parseResult be ParseText(offsetString, UTCOffset)
var match = OFFSET_TIMEZONE_FORMAT_REGEX.exec(offsetString);
// 3. If parseResult is a List of errors, return false
if (!match) {
return false;
}
// 4. Validate component ranges per ECMA-262 grammar
// Hour must be 0-23, Minute must be 0-59, Second must be 0-59
var hours = parseInt(match[2], 10);
var minutes = match[3] ? parseInt(match[3], 10) : 0;
var seconds = match[4] ? parseInt(match[4], 10) : 0;
if (hours > 23 || minutes > 59 || seconds > 59) {
return false;
}
// 5. Return true
return true;
// 1. If offsetString does not start with '+' or '-', return false
if (!OFFSET_TIMEZONE_PREFIX_REGEX.test(offsetString)) {
return false;
}
// 2. Let parseResult be ParseText(offsetString, UTCOffset)
const match = OFFSET_TIMEZONE_FORMAT_REGEX.exec(offsetString);
// 3. If parseResult is a List of errors, return false
if (!match) {
return false;
}
// 4. Validate component ranges per ECMA-262 grammar
// Hour must be 0-23, Minute must be 0-59, Second must be 0-59
const hours = parseInt(match[2], 10);
const minutes = match[3] ? parseInt(match[3], 10) : 0;
const seconds = match[4] ? parseInt(match[4], 10) : 0;
if (hours > 23 || minutes > 59 || seconds > 59) {
return false;
}
// 5. Return true
return true;
}
/**
* IsValidTimeZoneName ( timeZone )
* https://tc39.es/ecma402/#sec-isvalidtimezonename
*
* Extended to support UTC offset time zones per ECMA-402 PR #788 (ES2026).
* The abstract operation validates both:
* 1. UTC offset identifiers (e.g., "+01:00", "-05:30")
* 2. Available named time zone identifiers from IANA Time Zone Database
*
* @param tz - The timezone identifier to validate
* @param implDetails - Implementation details containing timezone data
* @returns true if timeZone is a valid identifier
*/
export function IsValidTimeZoneName(tz, _a) {
var zoneNamesFromData = _a.zoneNamesFromData, uppercaseLinks = _a.uppercaseLinks;
// 1. If IsTimeZoneOffsetString(timeZone) is true, return true
// Per ECMA-402 PR #788, UTC offset identifiers are valid
if (IsTimeZoneOffsetString(tz)) {
return true;
}
// 2. Let timeZones be AvailableNamedTimeZoneIdentifiers()
// 3. If timeZones contains an element equal to timeZone, return true
// NOTE: Implementation uses case-insensitive comparison per spec note
var uppercasedTz = tz.toUpperCase();
var zoneNames = new Set();
var linkNames = new Set();
zoneNamesFromData.map(function (z) { return z.toUpperCase(); }).forEach(function (z) { return zoneNames.add(z); });
Object.keys(uppercaseLinks).forEach(function (linkName) {
linkNames.add(linkName.toUpperCase());
zoneNames.add(uppercaseLinks[linkName].toUpperCase());
});
if (zoneNames.has(uppercasedTz) || linkNames.has(uppercasedTz)) {
return true;
}
// 4. Return false
return false;
* IsValidTimeZoneName ( timeZone )
* https://tc39.es/ecma402/#sec-isvalidtimezonename
*
* Extended to support UTC offset time zones per ECMA-402 PR #788 (ES2026).
* The abstract operation validates both:
* 1. UTC offset identifiers (e.g., "+01:00", "-05:30")
* 2. Available named time zone identifiers from IANA Time Zone Database
*
* @param tz - The timezone identifier to validate
* @param implDetails - Implementation details containing timezone data
* @returns true if timeZone is a valid identifier
*/
export function IsValidTimeZoneName(tz, { zoneNamesFromData, uppercaseLinks }) {
// 1. If IsTimeZoneOffsetString(timeZone) is true, return true
// Per ECMA-402 PR #788, UTC offset identifiers are valid
if (IsTimeZoneOffsetString(tz)) {
return true;
}
// 2. Let timeZones be AvailableNamedTimeZoneIdentifiers()
// 3. If timeZones contains an element equal to timeZone, return true
// NOTE: Implementation uses case-insensitive comparison per spec note
const uppercasedTz = tz.toUpperCase();
const zoneNames = new Set();
const linkNames = new Set();
zoneNamesFromData.map((z) => z.toUpperCase()).forEach((z) => zoneNames.add(z));
Object.keys(uppercaseLinks).forEach((linkName) => {
linkNames.add(linkName.toUpperCase());
zoneNames.add(uppercaseLinks[linkName].toUpperCase());
});
if (zoneNames.has(uppercasedTz) || linkNames.has(uppercasedTz)) {
return true;
}
// 4. Return false
return false;
}
/**
* https://tc39.es/ecma402/#sec-iswellformedcurrencycode
*/
* https://tc39.es/ecma402/#sec-iswellformedcurrencycode
*/
export declare function IsWellFormedCurrencyCode(currency: string): boolean;
/**
* This follows https://tc39.es/ecma402/#sec-case-sensitivity-and-case-mapping
* @param str string to convert
*/
* This follows https://tc39.es/ecma402/#sec-case-sensitivity-and-case-mapping
* @param str string to convert
*/
function toUpperCase(str) {
return str.replace(/([a-z])/g, function (_, c) { return c.toUpperCase(); });
return str.replace(/([a-z])/g, (_, c) => c.toUpperCase());
}
var NOT_A_Z_REGEX = /[^A-Z]/;
const NOT_A_Z_REGEX = /[^A-Z]/;
/**
* https://tc39.es/ecma402/#sec-iswellformedcurrencycode
*/
* https://tc39.es/ecma402/#sec-iswellformedcurrencycode
*/
export function IsWellFormedCurrencyCode(currency) {
currency = toUpperCase(currency);
if (currency.length !== 3) {
return false;
}
if (NOT_A_Z_REGEX.test(currency)) {
return false;
}
return true;
currency = toUpperCase(currency);
if (currency.length !== 3) {
return false;
}
if (NOT_A_Z_REGEX.test(currency)) {
return false;
}
return true;
}
/**
* https://tc39.es/ecma402/#sec-iswellformedunitidentifier
* @param unit
*/
* https://tc39.es/ecma402/#sec-iswellformedunitidentifier
* @param unit
*/
export declare function IsWellFormedUnitIdentifier(unit: string): boolean;

@@ -1,28 +0,27 @@

import { IsSanctionedSimpleUnitIdentifier } from './IsSanctionedSimpleUnitIdentifier.js';
import { IsSanctionedSimpleUnitIdentifier } from "./IsSanctionedSimpleUnitIdentifier.js";
/**
* This follows https://tc39.es/ecma402/#sec-case-sensitivity-and-case-mapping
* @param str string to convert
*/
* This follows https://tc39.es/ecma402/#sec-case-sensitivity-and-case-mapping
* @param str string to convert
*/
function toLowerCase(str) {
return str.replace(/([A-Z])/g, function (_, c) { return c.toLowerCase(); });
return str.replace(/([A-Z])/g, (_, c) => c.toLowerCase());
}
/**
* https://tc39.es/ecma402/#sec-iswellformedunitidentifier
* @param unit
*/
* https://tc39.es/ecma402/#sec-iswellformedunitidentifier
* @param unit
*/
export function IsWellFormedUnitIdentifier(unit) {
unit = toLowerCase(unit);
if (IsSanctionedSimpleUnitIdentifier(unit)) {
return true;
}
var units = unit.split('-per-');
if (units.length !== 2) {
return false;
}
var numerator = units[0], denominator = units[1];
if (!IsSanctionedSimpleUnitIdentifier(numerator) ||
!IsSanctionedSimpleUnitIdentifier(denominator)) {
return false;
}
return true;
unit = toLowerCase(unit);
if (IsSanctionedSimpleUnitIdentifier(unit)) {
return true;
}
const units = unit.split("-per-");
if (units.length !== 2) {
return false;
}
const [numerator, denominator] = units;
if (!IsSanctionedSimpleUnitIdentifier(numerator) || !IsSanctionedSimpleUnitIdentifier(denominator)) {
return false;
}
return true;
}

@@ -1,3 +0,3 @@

import { Decimal } from 'decimal.js';
import { UnsignedRoundingModeType } from '../types/number.js';
import type { Decimal } from "decimal.js";
import { type UnsignedRoundingModeType } from "../types/number.js";
export declare function ApplyUnsignedRoundingMode(x: Decimal, r1: Decimal, r2: Decimal, unsignedRoundingMode: UnsignedRoundingModeType): Decimal;

@@ -1,33 +0,33 @@

import { invariant } from '../utils.js';
import "../types/number.js";
import { invariant } from "../utils.js";
export function ApplyUnsignedRoundingMode(x, r1, r2, unsignedRoundingMode) {
if (x.eq(r1))
return r1;
invariant(r1.lessThan(x) && x.lessThan(r2), "x should be between r1 and r2 but x=".concat(x, ", r1=").concat(r1, ", r2=").concat(r2));
if (unsignedRoundingMode === 'zero') {
return r1;
}
if (unsignedRoundingMode === 'infinity') {
return r2;
}
var d1 = x.minus(r1);
var d2 = r2.minus(x);
if (d1.lessThan(d2)) {
return r1;
}
if (d2.lessThan(d1)) {
return r2;
}
invariant(d1.eq(d2), 'd1 should be equal to d2');
if (unsignedRoundingMode === 'half-zero') {
return r1;
}
if (unsignedRoundingMode === 'half-infinity') {
return r2;
}
invariant(unsignedRoundingMode === 'half-even', 'unsignedRoundingMode should be half-even');
var cardinality = r1.div(r2.minus(r1)).mod(2);
if (cardinality.isZero()) {
return r1;
}
return r2;
if (x.eq(r1)) return r1;
invariant(r1.lessThan(x) && x.lessThan(r2), `x should be between r1 and r2 but x=${x}, r1=${r1}, r2=${r2}`);
if (unsignedRoundingMode === "zero") {
return r1;
}
if (unsignedRoundingMode === "infinity") {
return r2;
}
const d1 = x.minus(r1);
const d2 = r2.minus(x);
if (d1.lessThan(d2)) {
return r1;
}
if (d2.lessThan(d1)) {
return r2;
}
invariant(d1.eq(d2), "d1 should be equal to d2");
if (unsignedRoundingMode === "half-zero") {
return r1;
}
if (unsignedRoundingMode === "half-infinity") {
return r2;
}
invariant(unsignedRoundingMode === "half-even", "unsignedRoundingMode should be half-even");
const cardinality = r1.div(r2.minus(r1)).mod(2);
if (cardinality.isZero()) {
return r1;
}
return r2;
}

@@ -1,8 +0,8 @@

import { NumberFormatInternal, NumberFormatPart } from '../types/number.js';
import { type NumberFormatInternal, type NumberFormatPart } from "../types/number.js";
/**
* https://tc39.es/ecma402/#sec-collapsenumberrange
* LDML: https://unicode-org.github.io/cldr/ldml/tr35-numbers.html#collapsing-number-ranges
*/
export declare function CollapseNumberRange(numberFormat: Intl.NumberFormat, result: NumberFormatPart[], { getInternalSlots, }: {
getInternalSlots(nf: Intl.NumberFormat): NumberFormatInternal;
* https://tc39.es/ecma402/#sec-collapsenumberrange
* LDML: https://unicode-org.github.io/cldr/ldml/tr35-numbers.html#collapsing-number-ranges
*/
export declare function CollapseNumberRange(numberFormat: Intl.NumberFormat, result: NumberFormatPart[], { getInternalSlots }: {
getInternalSlots(nf: Intl.NumberFormat): NumberFormatInternal;
}): NumberFormatPart[];

@@ -1,50 +0,50 @@

var PART_TYPES_TO_COLLAPSE = new Set([
'unit',
'exponentMinusSign',
'minusSign',
'plusSign',
'percentSign',
'exponentSeparator',
'percent',
'percentSign',
'currency',
'literal',
import "../types/number.js";
const PART_TYPES_TO_COLLAPSE = new Set([
"unit",
"exponentMinusSign",
"minusSign",
"plusSign",
"percentSign",
"exponentSeparator",
"percent",
"percentSign",
"currency",
"literal"
]);
/**
* https://tc39.es/ecma402/#sec-collapsenumberrange
* LDML: https://unicode-org.github.io/cldr/ldml/tr35-numbers.html#collapsing-number-ranges
*/
export function CollapseNumberRange(numberFormat, result, _a) {
var getInternalSlots = _a.getInternalSlots;
var internalSlots = getInternalSlots(numberFormat);
var symbols = internalSlots.dataLocaleData.numbers.symbols[internalSlots.numberingSystem];
var rangeSignRegex = new RegExp("s?[".concat(symbols.rangeSign, "]s?"));
var rangeSignIndex = result.findIndex(function (r) { return r.type === 'literal' && rangeSignRegex.test(r.value); });
var prefixSignParts = [];
for (var i = rangeSignIndex - 1; i >= 0; i--) {
if (!PART_TYPES_TO_COLLAPSE.has(result[i].type)) {
break;
}
prefixSignParts.unshift(result[i]);
}
// Don't collapse if it's a single code point
if (Array.from(prefixSignParts.map(function (p) { return p.value; }).join('')).length > 1) {
var newResult = Array.from(result);
newResult.splice(rangeSignIndex - prefixSignParts.length, prefixSignParts.length);
return newResult;
}
var suffixSignParts = [];
for (var i = rangeSignIndex + 1; i < result.length; i++) {
if (!PART_TYPES_TO_COLLAPSE.has(result[i].type)) {
break;
}
suffixSignParts.push(result[i]);
}
// Don't collapse if it's a single code point
if (Array.from(suffixSignParts.map(function (p) { return p.value; }).join('')).length > 1) {
var newResult = Array.from(result);
newResult.splice(rangeSignIndex + 1, suffixSignParts.length);
return newResult;
}
return result;
* https://tc39.es/ecma402/#sec-collapsenumberrange
* LDML: https://unicode-org.github.io/cldr/ldml/tr35-numbers.html#collapsing-number-ranges
*/
export function CollapseNumberRange(numberFormat, result, { getInternalSlots }) {
const internalSlots = getInternalSlots(numberFormat);
const symbols = internalSlots.dataLocaleData.numbers.symbols[internalSlots.numberingSystem];
const rangeSignRegex = new RegExp(`s?[${symbols.rangeSign}]s?`);
const rangeSignIndex = result.findIndex((r) => r.type === "literal" && rangeSignRegex.test(r.value));
let prefixSignParts = [];
for (let i = rangeSignIndex - 1; i >= 0; i--) {
if (!PART_TYPES_TO_COLLAPSE.has(result[i].type)) {
break;
}
prefixSignParts.unshift(result[i]);
}
// Don't collapse if it's a single code point
if (Array.from(prefixSignParts.map((p) => p.value).join("")).length > 1) {
const newResult = Array.from(result);
newResult.splice(rangeSignIndex - prefixSignParts.length, prefixSignParts.length);
return newResult;
}
let suffixSignParts = [];
for (let i = rangeSignIndex + 1; i < result.length; i++) {
if (!PART_TYPES_TO_COLLAPSE.has(result[i].type)) {
break;
}
suffixSignParts.push(result[i]);
}
// Don't collapse if it's a single code point
if (Array.from(suffixSignParts.map((p) => p.value).join("")).length > 1) {
const newResult = Array.from(result);
newResult.splice(rangeSignIndex + 1, suffixSignParts.length);
return newResult;
}
return result;
}

@@ -1,10 +0,10 @@

import { Decimal } from 'decimal.js';
import { NumberFormatInternal } from '../types/number.js';
import { Decimal } from "decimal.js";
import { type NumberFormatInternal } from "../types/number.js";
/**
* The abstract operation ComputeExponent computes an exponent (power of ten) by which to scale x
* according to the number formatting settings. It handles cases such as 999 rounding up to 1000,
* requiring a different exponent.
*
* NOT IN SPEC: it returns [exponent, magnitude].
*/
* The abstract operation ComputeExponent computes an exponent (power of ten) by which to scale x
* according to the number formatting settings. It handles cases such as 999 rounding up to 1000,
* requiring a different exponent.
*
* NOT IN SPEC: it returns [exponent, magnitude].
*/
export declare function ComputeExponent(internalSlots: NumberFormatInternal, x: Decimal): [number, number];

@@ -1,61 +0,51 @@

import { Decimal } from 'decimal.js';
import { ComputeExponentForMagnitude } from './ComputeExponentForMagnitude.js';
import { FormatNumericToString } from './FormatNumericToString.js';
import { getPowerOf10 } from './decimal-cache.js';
import { Decimal } from "decimal.js";
import "../types/number.js";
import { ComputeExponentForMagnitude } from "./ComputeExponentForMagnitude.js";
import { FormatNumericToString } from "./FormatNumericToString.js";
import { getPowerOf10 } from "./decimal-cache.js";
/**
* The abstract operation ComputeExponent computes an exponent (power of ten) by which to scale x
* according to the number formatting settings. It handles cases such as 999 rounding up to 1000,
* requiring a different exponent.
*
* NOT IN SPEC: it returns [exponent, magnitude].
*/
* The abstract operation ComputeExponent computes an exponent (power of ten) by which to scale x
* according to the number formatting settings. It handles cases such as 999 rounding up to 1000,
* requiring a different exponent.
*
* NOT IN SPEC: it returns [exponent, magnitude].
*/
export function ComputeExponent(internalSlots, x) {
if (x.isZero()) {
return [0, 0];
}
if (x.isNegative()) {
x = x.negated();
}
// Fast path for simple numbers
// If x can be represented as a safe integer, use native Math.log10
var xNum = x.toNumber();
var magnitude;
if (Number.isFinite(xNum) &&
Number.isSafeInteger(xNum) &&
xNum > 0 &&
xNum <= 999999) {
// Use fast native logarithm for simple positive integers
var magNum = Math.floor(Math.log10(xNum));
magnitude = new Decimal(magNum);
}
else {
magnitude = x.log(10).floor();
}
var exponent = ComputeExponentForMagnitude(internalSlots, magnitude);
// Preserve more precision by doing multiplication when exponent is negative.
x = x.times(getPowerOf10(-exponent));
var formatNumberResult = FormatNumericToString(internalSlots, x);
if (formatNumberResult.roundedNumber.isZero()) {
return [exponent, magnitude.toNumber()];
}
// Fast path for simple rounded numbers
var roundedNum = formatNumberResult.roundedNumber.toNumber();
var newMagnitude;
if (Number.isFinite(roundedNum) &&
Number.isSafeInteger(roundedNum) &&
roundedNum > 0 &&
roundedNum <= 999999) {
var newMagNum = Math.floor(Math.log10(roundedNum));
newMagnitude = new Decimal(newMagNum);
}
else {
newMagnitude = formatNumberResult.roundedNumber.log(10).floor();
}
if (newMagnitude.eq(magnitude.minus(exponent))) {
return [exponent, magnitude.toNumber()];
}
return [
ComputeExponentForMagnitude(internalSlots, magnitude.plus(1)),
magnitude.plus(1).toNumber(),
];
if (x.isZero()) {
return [0, 0];
}
if (x.isNegative()) {
x = x.negated();
}
// Fast path for simple numbers
// If x can be represented as a safe integer, use native Math.log10
const xNum = x.toNumber();
let magnitude;
if (Number.isFinite(xNum) && Number.isSafeInteger(xNum) && xNum > 0 && xNum <= 999999) {
// Use fast native logarithm for simple positive integers
const magNum = Math.floor(Math.log10(xNum));
magnitude = new Decimal(magNum);
} else {
magnitude = x.log(10).floor();
}
const exponent = ComputeExponentForMagnitude(internalSlots, magnitude);
// Preserve more precision by doing multiplication when exponent is negative.
x = x.times(getPowerOf10(-exponent));
const formatNumberResult = FormatNumericToString(internalSlots, x);
if (formatNumberResult.roundedNumber.isZero()) {
return [exponent, magnitude.toNumber()];
}
// Fast path for simple rounded numbers
const roundedNum = formatNumberResult.roundedNumber.toNumber();
let newMagnitude;
if (Number.isFinite(roundedNum) && Number.isSafeInteger(roundedNum) && roundedNum > 0 && roundedNum <= 999999) {
const newMagNum = Math.floor(Math.log10(roundedNum));
newMagnitude = new Decimal(newMagNum);
} else {
newMagnitude = formatNumberResult.roundedNumber.log(10).floor();
}
if (newMagnitude.eq(magnitude.minus(exponent))) {
return [exponent, magnitude.toNumber()];
}
return [ComputeExponentForMagnitude(internalSlots, magnitude.plus(1)), magnitude.plus(1).toNumber()];
}

@@ -1,8 +0,8 @@

import { Decimal } from 'decimal.js';
import { NumberFormatInternal } from '../types/number.js';
import { Decimal } from "decimal.js";
import { type NumberFormatInternal } from "../types/number.js";
/**
* The abstract operation ComputeExponentForMagnitude computes an exponent by which to scale a
* number of the given magnitude (power of ten of the most significant digit) according to the
* locale and the desired notation (scientific, engineering, or compact).
*/
* The abstract operation ComputeExponentForMagnitude computes an exponent by which to scale a
* number of the given magnitude (power of ten of the most significant digit) according to the
* locale and the desired notation (scientific, engineering, or compact).
*/
export declare function ComputeExponentForMagnitude(internalSlots: NumberFormatInternal, magnitude: Decimal): number;

@@ -1,75 +0,67 @@

import { Decimal } from 'decimal.js';
import { invariant } from '../utils.js';
import { getPowerOf10 } from './decimal-cache.js';
Decimal.set({
toExpPos: 100,
});
import { Decimal } from "decimal.js";
import "../types/number.js";
import { invariant } from "../utils.js";
import { getPowerOf10 } from "./decimal-cache.js";
Decimal.set({ toExpPos: 100 });
/**
* The abstract operation ComputeExponentForMagnitude computes an exponent by which to scale a
* number of the given magnitude (power of ten of the most significant digit) according to the
* locale and the desired notation (scientific, engineering, or compact).
*/
* The abstract operation ComputeExponentForMagnitude computes an exponent by which to scale a
* number of the given magnitude (power of ten of the most significant digit) according to the
* locale and the desired notation (scientific, engineering, or compact).
*/
export function ComputeExponentForMagnitude(internalSlots, magnitude) {
var notation = internalSlots.notation, dataLocaleData = internalSlots.dataLocaleData, numberingSystem = internalSlots.numberingSystem;
switch (notation) {
case 'standard':
return 0;
case 'scientific':
return magnitude.toNumber();
case 'engineering':
var thousands = magnitude.div(3).floor();
return thousands.times(3).toNumber();
default: {
invariant(notation === 'compact', 'Invalid notation');
// Let exponent be an implementation- and locale-dependent (ILD) integer by which to scale a
// number of the given magnitude in compact notation for the current locale.
var compactDisplay = internalSlots.compactDisplay, style = internalSlots.style, currencyDisplay = internalSlots.currencyDisplay;
var thresholdMap = void 0;
if (style === 'currency' && currencyDisplay !== 'name') {
var currency = dataLocaleData.numbers.currency[numberingSystem] ||
dataLocaleData.numbers.currency[dataLocaleData.numbers.nu[0]];
thresholdMap = currency.short;
}
else {
var decimal = dataLocaleData.numbers.decimal[numberingSystem] ||
dataLocaleData.numbers.decimal[dataLocaleData.numbers.nu[0]];
thresholdMap = compactDisplay === 'long' ? decimal.long : decimal.short;
}
if (!thresholdMap) {
return 0;
}
var num = getPowerOf10(magnitude).toString();
var thresholds = Object.keys(thresholdMap); // TODO: this can be pre-processed
if (num < thresholds[0]) {
return 0;
}
if (num > thresholds[thresholds.length - 1]) {
// GH #4236: When number exceeds max threshold, use the exponent
// corresponding to the largest available threshold in locale data.
// Calculate exponent the same way as for normal thresholds (lines 70-73).
var magnitudeKey_1 = thresholds[thresholds.length - 1];
var compactPattern_1 = thresholdMap[magnitudeKey_1].other;
if (compactPattern_1 === '0') {
return 0;
}
return (magnitudeKey_1.length -
thresholdMap[magnitudeKey_1].other.match(/0+/)[0].length);
}
var i = thresholds.indexOf(num);
if (i === -1) {
return 0;
}
// See https://unicode.org/reports/tr35/tr35-numbers.html#Compact_Number_Formats
// Special handling if the pattern is precisely `0`.
var magnitudeKey = thresholds[i];
// TODO: do we need to handle plural here?
var compactPattern = thresholdMap[magnitudeKey].other;
if (compactPattern === '0') {
return 0;
}
// Example: in zh-TW, `10000000` maps to `0000萬`. So we need to return 8 - 4 = 4 here.
return (magnitudeKey.length -
thresholdMap[magnitudeKey].other.match(/0+/)[0].length);
}
}
const { notation, dataLocaleData, numberingSystem } = internalSlots;
switch (notation) {
case "standard": return 0;
case "scientific": return magnitude.toNumber();
case "engineering":
const thousands = magnitude.div(3).floor();
return thousands.times(3).toNumber();
default: {
invariant(notation === "compact", "Invalid notation");
// Let exponent be an implementation- and locale-dependent (ILD) integer by which to scale a
// number of the given magnitude in compact notation for the current locale.
const { compactDisplay, style, currencyDisplay } = internalSlots;
let thresholdMap;
if (style === "currency" && currencyDisplay !== "name") {
const currency = dataLocaleData.numbers.currency[numberingSystem] || dataLocaleData.numbers.currency[dataLocaleData.numbers.nu[0]];
thresholdMap = currency.short;
} else {
const decimal = dataLocaleData.numbers.decimal[numberingSystem] || dataLocaleData.numbers.decimal[dataLocaleData.numbers.nu[0]];
thresholdMap = compactDisplay === "long" ? decimal.long : decimal.short;
}
if (!thresholdMap) {
return 0;
}
const num = getPowerOf10(magnitude).toString();
const thresholds = Object.keys(thresholdMap);
if (num < thresholds[0]) {
return 0;
}
if (num > thresholds[thresholds.length - 1]) {
// GH #4236: When number exceeds max threshold, use the exponent
// corresponding to the largest available threshold in locale data.
// Calculate exponent the same way as for normal thresholds (lines 70-73).
const magnitudeKey = thresholds[thresholds.length - 1];
const compactPattern = thresholdMap[magnitudeKey].other;
if (compactPattern === "0") {
return 0;
}
return magnitudeKey.length - thresholdMap[magnitudeKey].other.match(/0+/)[0].length;
}
const i = thresholds.indexOf(num);
if (i === -1) {
return 0;
}
// See https://unicode.org/reports/tr35/tr35-numbers.html#Compact_Number_Formats
// Special handling if the pattern is precisely `0`.
const magnitudeKey = thresholds[i];
// TODO: do we need to handle plural here?
const compactPattern = thresholdMap[magnitudeKey].other;
if (compactPattern === "0") {
return 0;
}
// Example: in zh-TW, `10000000` maps to `0000萬`. So we need to return 8 - 4 = 4 here.
return magnitudeKey.length - thresholdMap[magnitudeKey].other.match(/0+/)[0].length;
}
}
}
/**
* https://tc39.es/ecma402/#sec-currencydigits
*/
* https://tc39.es/ecma402/#sec-currencydigits
*/
export declare function CurrencyDigits(c: string, { currencyDigitsData }: {
currencyDigitsData: Record<string, number>;
currencyDigitsData: Record<string, number>;
}): number;

@@ -1,10 +0,7 @@

import { HasOwnProperty } from '../262.js';
import { HasOwnProperty } from "../262.js";
/**
* https://tc39.es/ecma402/#sec-currencydigits
*/
export function CurrencyDigits(c, _a) {
var currencyDigitsData = _a.currencyDigitsData;
return HasOwnProperty(currencyDigitsData, c)
? currencyDigitsData[c]
: 2;
* https://tc39.es/ecma402/#sec-currencydigits
*/
export function CurrencyDigits(c, { currencyDigitsData }) {
return HasOwnProperty(currencyDigitsData, c) ? currencyDigitsData[c] : 2;
}

@@ -1,12 +0,12 @@

import { Decimal } from 'decimal.js';
import { Decimal } from "decimal.js";
/**
* Cached function to compute powers of 10 for Decimal.js operations.
* This cache significantly reduces overhead in ComputeExponent and ToRawFixed
* by memoizing expensive Decimal.pow(10, n) calculations.
*
* Common exponents (e.g., -20 to 20) are used repeatedly in number formatting,
* so caching provides substantial performance benefits.
*
* @param exponent - Can be a number or Decimal. If Decimal, it will be converted to string for cache key.
*/
* Cached function to compute powers of 10 for Decimal.js operations.
* This cache significantly reduces overhead in ComputeExponent and ToRawFixed
* by memoizing expensive Decimal.pow(10, n) calculations.
*
* Common exponents (e.g., -20 to 20) are used repeatedly in number formatting,
* so caching provides substantial performance benefits.
*
* @param exponent - Can be a number or Decimal. If Decimal, it will be converted to string for cache key.
*/
export declare const getPowerOf10: (exponent: number | Decimal) => Decimal;

@@ -1,15 +0,15 @@

import { Decimal } from 'decimal.js';
import { memoize } from '@formatjs/fast-memoize';
import { Decimal } from "decimal.js";
import { memoize } from "@formatjs/fast-memoize";
/**
* Cached function to compute powers of 10 for Decimal.js operations.
* This cache significantly reduces overhead in ComputeExponent and ToRawFixed
* by memoizing expensive Decimal.pow(10, n) calculations.
*
* Common exponents (e.g., -20 to 20) are used repeatedly in number formatting,
* so caching provides substantial performance benefits.
*
* @param exponent - Can be a number or Decimal. If Decimal, it will be converted to string for cache key.
*/
export var getPowerOf10 = memoize(function (exponent) {
return Decimal.pow(10, exponent);
* Cached function to compute powers of 10 for Decimal.js operations.
* This cache significantly reduces overhead in ComputeExponent and ToRawFixed
* by memoizing expensive Decimal.pow(10, n) calculations.
*
* Common exponents (e.g., -20 to 20) are used repeatedly in number formatting,
* so caching provides substantial performance benefits.
*
* @param exponent - Can be a number or Decimal. If Decimal, it will be converted to string for cache key.
*/
export const getPowerOf10 = memoize((exponent) => {
return Decimal.pow(10, exponent);
});

@@ -1,67 +0,782 @@

export var digitMapping = {
adlm: ['𞥐', '𞥑', '𞥒', '𞥓', '𞥔', '𞥕', '𞥖', '𞥗', '𞥘', '𞥙'],
ahom: ['𑜰', '𑜱', '𑜲', '𑜳', '𑜴', '𑜵', '𑜶', '𑜷', '𑜸', '𑜹'],
arab: ['٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'],
arabext: ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'],
bali: ['᭐', '᭑', '᭒', '᭓', '᭔', '᭕', '᭖', '᭗', '᭘', '᭙'],
beng: ['০', '১', '২', '৩', '৪', '৫', '৬', '৭', '৮', '৯'],
bhks: ['𑱐', '𑱑', '𑱒', '𑱓', '𑱔', '𑱕', '𑱖', '𑱗', '𑱘', '𑱙'],
brah: ['𑁦', '𑁧', '𑁨', '𑁩', '𑁪', '𑁫', '𑁬', '𑁭', '𑁮', '𑁯'],
cakm: ['𑄶', '𑄷', '𑄸', '𑄹', '𑄺', '𑄻', '𑄼', '𑄽', '𑄾', '𑄿'],
cham: ['꩐', '꩑', '꩒', '꩓', '꩔', '꩕', '꩖', '꩗', '꩘', '꩙'],
deva: ['०', '१', '२', '३', '४', '५', '६', '७', '८', '९'],
diak: ['𑥐', '𑥑', '𑥒', '𑥓', '𑥔', '𑥕', '𑥖', '𑥗', '𑥘', '𑥙'],
fullwide: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
gong: ['𑶠', '𑶡', '𑶢', '𑶣', '𑶤', '𑶥', '𑶦', '𑶧', '𑶨', '𑶩'],
gonm: ['𑵐', '𑵑', '𑵒', '𑵓', '𑵔', '𑵕', '𑵖', '𑵗', '𑵘', '𑵙'],
gujr: ['૦', '૧', '૨', '૩', '૪', '૫', '૬', '૭', '૮', '૯'],
guru: ['੦', '੧', '੨', '੩', '੪', '੫', '੬', '੭', '੮', '੯'],
hanidec: ['〇', '一', '二', '三', '四', '五', '六', '七', '八', '九'],
hmng: ['𖭐', '𖭑', '𖭒', '𖭓', '𖭔', '𖭕', '𖭖', '𖭗', '𖭘', '𖭙'],
hmnp: ['𞅀', '𞅁', '𞅂', '𞅃', '𞅄', '𞅅', '𞅆', '𞅇', '𞅈', '𞅉'],
java: ['꧐', '꧑', '꧒', '꧓', '꧔', '꧕', '꧖', '꧗', '꧘', '꧙'],
kali: ['꤀', '꤁', '꤂', '꤃', '꤄', '꤅', '꤆', '꤇', '꤈', '꤉'],
khmr: ['០', '១', '២', '៣', '៤', '៥', '៦', '៧', '៨', '៩'],
knda: ['೦', '೧', '೨', '೩', '೪', '೫', '೬', '೭', '೮', '೯'],
lana: ['᪀', '᪁', '᪂', '᪃', '᪄', '᪅', '᪆', '᪇', '᪈', '᪉'],
lanatham: ['᪐', '᪑', '᪒', '᪓', '᪔', '᪕', '᪖', '᪗', '᪘', '᪙'],
laoo: ['໐', '໑', '໒', '໓', '໔', '໕', '໖', '໗', '໘', '໙'],
lepc: ['᪐', '᪑', '᪒', '᪓', '᪔', '᪕', '᪖', '᪗', '᪘', '᪙'],
limb: ['᥆', '᥇', '᥈', '᥉', '᥊', '᥋', '᥌', '᥍', '᥎', '᥏'],
mathbold: ['𝟎', '𝟏', '𝟐', '𝟑', '𝟒', '𝟓', '𝟔', '𝟕', '𝟖', '𝟗'],
mathdbl: ['𝟘', '𝟙', '𝟚', '𝟛', '𝟜', '𝟝', '𝟞', '𝟟', '𝟠', '𝟡'],
mathmono: ['𝟶', '𝟷', '𝟸', '𝟹', '𝟺', '𝟻', '𝟼', '𝟽', '𝟾', '𝟿'],
mathsanb: ['𝟬', '𝟭', '𝟮', '𝟯', '𝟰', '𝟱', '𝟲', '𝟳', '𝟴', '𝟵'],
mathsans: ['𝟢', '𝟣', '𝟤', '𝟥', '𝟦', '𝟧', '𝟨', '𝟩', '𝟪', '𝟫'],
mlym: ['൦', '൧', '൨', '൩', '൪', '൫', '൬', '൭', '൮', '൯'],
modi: ['𑙐', '𑙑', '𑙒', '𑙓', '𑙔', '𑙕', '𑙖', '𑙗', '𑙘', '𑙙'],
mong: ['᠐', '᠑', '᠒', '᠓', '᠔', '᠕', '᠖', '᠗', '᠘', '᠙'],
mroo: ['𖩠', '𖩡', '𖩢', '𖩣', '𖩤', '𖩥', '𖩦', '𖩧', '𖩨', '𖩩'],
mtei: ['꯰', '꯱', '꯲', '꯳', '꯴', '꯵', '꯶', '꯷', '꯸', '꯹'],
mymr: ['၀', '၁', '၂', '၃', '၄', '၅', '၆', '၇', '၈', '၉'],
mymrshan: ['႐', '႑', '႒', '႓', '႔', '႕', '႖', '႗', '႘', '႙'],
mymrtlng: ['꧰', '꧱', '꧲', '꧳', '꧴', '꧵', '꧶', '꧷', '꧸', '꧹'],
newa: ['𑑐', '𑑑', '𑑒', '𑑓', '𑑔', '𑑕', '𑑖', '𑑗', '𑑘', '𑑙'],
nkoo: ['߀', '߁', '߂', '߃', '߄', '߅', '߆', '߇', '߈', '߉'],
olck: ['᱐', '᱑', '᱒', '᱓', '᱔', '᱕', '᱖', '᱗', '᱘', '᱙'],
orya: ['୦', '୧', '୨', '୩', '୪', '୫', '୬', '୭', '୮', '୯'],
osma: ['𐒠', '𐒡', '𐒢', '𐒣', '𐒤', '𐒥', '𐒦', '𐒧', '𐒨', '𐒩'],
rohg: ['𐴰', '𐴱', '𐴲', '𐴳', '𐴴', '𐴵', '𐴶', '𐴷', '𐴸', '𐴹'],
saur: ['꣐', '꣑', '꣒', '꣓', '꣔', '꣕', '꣖', '꣗', '꣘', '꣙'],
segment: ['🯰', '🯱', '🯲', '🯳', '🯴', '🯵', '🯶', '🯷', '🯸', '🯹'],
shrd: ['𑇐', '𑇑', '𑇒', '𑇓', '𑇔', '𑇕', '𑇖', '𑇗', '𑇘', '𑇙'],
sind: ['𑋰', '𑋱', '𑋲', '𑋳', '𑋴', '𑋵', '𑋶', '𑋷', '𑋸', '𑋹'],
sinh: ['෦', '෧', '෨', '෩', '෪', '෫', '෬', '෭', '෮', '෯'],
sora: ['𑃰', '𑃱', '𑃲', '𑃳', '𑃴', '𑃵', '𑃶', '𑃷', '𑃸', '𑃹'],
sund: ['᮰', '᮱', '᮲', '᮳', '᮴', '᮵', '᮶', '᮷', '᮸', '᮹'],
takr: ['𑛀', '𑛁', '𑛂', '𑛃', '𑛄', '𑛅', '𑛆', '𑛇', '𑛈', '𑛉'],
talu: ['᧐', '᧑', '᧒', '᧓', '᧔', '᧕', '᧖', '᧗', '᧘', '᧙'],
tamldec: ['௦', '௧', '௨', '௩', '௪', '௫', '௬', '௭', '௮', '௯'],
telu: ['౦', '౧', '౨', '౩', '౪', '౫', '౬', '౭', '౮', '౯'],
thai: ['๐', '๑', '๒', '๓', '๔', '๕', '๖', '๗', '๘', '๙'],
tibt: ['༠', '༡', '༢', '༣', '༤', '༥', '༦', '༧', '༨', '༩'],
tirh: ['𑓐', '𑓑', '𑓒', '𑓓', '𑓔', '𑓕', '𑓖', '𑓗', '𑓘', '𑓙'],
vaii: ['ᘠ', 'ᘡ', 'ᘢ', 'ᘣ', 'ᘤ', 'ᘥ', 'ᘦ', 'ᘧ', 'ᘨ', 'ᘩ'],
wara: ['𑣠', '𑣡', '𑣢', '𑣣', '𑣤', '𑣥', '𑣦', '𑣧', '𑣨', '𑣩'],
wcho: ['𞋰', '𞋱', '𞋲', '𞋳', '𞋴', '𞋵', '𞋶', '𞋷', '𞋸', '𞋹'],
export const digitMapping = {
adlm: [
"𞥐",
"𞥑",
"𞥒",
"𞥓",
"𞥔",
"𞥕",
"𞥖",
"𞥗",
"𞥘",
"𞥙"
],
ahom: [
"𑜰",
"𑜱",
"𑜲",
"𑜳",
"𑜴",
"𑜵",
"𑜶",
"𑜷",
"𑜸",
"𑜹"
],
arab: [
"٠",
"١",
"٢",
"٣",
"٤",
"٥",
"٦",
"٧",
"٨",
"٩"
],
arabext: [
"۰",
"۱",
"۲",
"۳",
"۴",
"۵",
"۶",
"۷",
"۸",
"۹"
],
bali: [
"᭐",
"᭑",
"᭒",
"᭓",
"᭔",
"᭕",
"᭖",
"᭗",
"᭘",
"᭙"
],
beng: [
"০",
"১",
"২",
"৩",
"৪",
"৫",
"৬",
"৭",
"৮",
"৯"
],
bhks: [
"𑱐",
"𑱑",
"𑱒",
"𑱓",
"𑱔",
"𑱕",
"𑱖",
"𑱗",
"𑱘",
"𑱙"
],
brah: [
"𑁦",
"𑁧",
"𑁨",
"𑁩",
"𑁪",
"𑁫",
"𑁬",
"𑁭",
"𑁮",
"𑁯"
],
cakm: [
"𑄶",
"𑄷",
"𑄸",
"𑄹",
"𑄺",
"𑄻",
"𑄼",
"𑄽",
"𑄾",
"𑄿"
],
cham: [
"꩐",
"꩑",
"꩒",
"꩓",
"꩔",
"꩕",
"꩖",
"꩗",
"꩘",
"꩙"
],
deva: [
"०",
"१",
"२",
"३",
"४",
"५",
"६",
"७",
"८",
"९"
],
diak: [
"𑥐",
"𑥑",
"𑥒",
"𑥓",
"𑥔",
"𑥕",
"𑥖",
"𑥗",
"𑥘",
"𑥙"
],
fullwide: [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9"
],
gong: [
"𑶠",
"𑶡",
"𑶢",
"𑶣",
"𑶤",
"𑶥",
"𑶦",
"𑶧",
"𑶨",
"𑶩"
],
gonm: [
"𑵐",
"𑵑",
"𑵒",
"𑵓",
"𑵔",
"𑵕",
"𑵖",
"𑵗",
"𑵘",
"𑵙"
],
gujr: [
"૦",
"૧",
"૨",
"૩",
"૪",
"૫",
"૬",
"૭",
"૮",
"૯"
],
guru: [
"੦",
"੧",
"੨",
"੩",
"੪",
"੫",
"੬",
"੭",
"੮",
"੯"
],
hanidec: [
"〇",
"一",
"二",
"三",
"四",
"五",
"六",
"七",
"八",
"九"
],
hmng: [
"𖭐",
"𖭑",
"𖭒",
"𖭓",
"𖭔",
"𖭕",
"𖭖",
"𖭗",
"𖭘",
"𖭙"
],
hmnp: [
"𞅀",
"𞅁",
"𞅂",
"𞅃",
"𞅄",
"𞅅",
"𞅆",
"𞅇",
"𞅈",
"𞅉"
],
java: [
"꧐",
"꧑",
"꧒",
"꧓",
"꧔",
"꧕",
"꧖",
"꧗",
"꧘",
"꧙"
],
kali: [
"꤀",
"꤁",
"꤂",
"꤃",
"꤄",
"꤅",
"꤆",
"꤇",
"꤈",
"꤉"
],
khmr: [
"០",
"១",
"២",
"៣",
"៤",
"៥",
"៦",
"៧",
"៨",
"៩"
],
knda: [
"೦",
"೧",
"೨",
"೩",
"೪",
"೫",
"೬",
"೭",
"೮",
"೯"
],
lana: [
"᪀",
"᪁",
"᪂",
"᪃",
"᪄",
"᪅",
"᪆",
"᪇",
"᪈",
"᪉"
],
lanatham: [
"᪐",
"᪑",
"᪒",
"᪓",
"᪔",
"᪕",
"᪖",
"᪗",
"᪘",
"᪙"
],
laoo: [
"໐",
"໑",
"໒",
"໓",
"໔",
"໕",
"໖",
"໗",
"໘",
"໙"
],
lepc: [
"᪐",
"᪑",
"᪒",
"᪓",
"᪔",
"᪕",
"᪖",
"᪗",
"᪘",
"᪙"
],
limb: [
"᥆",
"᥇",
"᥈",
"᥉",
"᥊",
"᥋",
"᥌",
"᥍",
"᥎",
"᥏"
],
mathbold: [
"𝟎",
"𝟏",
"𝟐",
"𝟑",
"𝟒",
"𝟓",
"𝟔",
"𝟕",
"𝟖",
"𝟗"
],
mathdbl: [
"𝟘",
"𝟙",
"𝟚",
"𝟛",
"𝟜",
"𝟝",
"𝟞",
"𝟟",
"𝟠",
"𝟡"
],
mathmono: [
"𝟶",
"𝟷",
"𝟸",
"𝟹",
"𝟺",
"𝟻",
"𝟼",
"𝟽",
"𝟾",
"𝟿"
],
mathsanb: [
"𝟬",
"𝟭",
"𝟮",
"𝟯",
"𝟰",
"𝟱",
"𝟲",
"𝟳",
"𝟴",
"𝟵"
],
mathsans: [
"𝟢",
"𝟣",
"𝟤",
"𝟥",
"𝟦",
"𝟧",
"𝟨",
"𝟩",
"𝟪",
"𝟫"
],
mlym: [
"൦",
"൧",
"൨",
"൩",
"൪",
"൫",
"൬",
"൭",
"൮",
"൯"
],
modi: [
"𑙐",
"𑙑",
"𑙒",
"𑙓",
"𑙔",
"𑙕",
"𑙖",
"𑙗",
"𑙘",
"𑙙"
],
mong: [
"᠐",
"᠑",
"᠒",
"᠓",
"᠔",
"᠕",
"᠖",
"᠗",
"᠘",
"᠙"
],
mroo: [
"𖩠",
"𖩡",
"𖩢",
"𖩣",
"𖩤",
"𖩥",
"𖩦",
"𖩧",
"𖩨",
"𖩩"
],
mtei: [
"꯰",
"꯱",
"꯲",
"꯳",
"꯴",
"꯵",
"꯶",
"꯷",
"꯸",
"꯹"
],
mymr: [
"၀",
"၁",
"၂",
"၃",
"၄",
"၅",
"၆",
"၇",
"၈",
"၉"
],
mymrshan: [
"႐",
"႑",
"႒",
"႓",
"႔",
"႕",
"႖",
"႗",
"႘",
"႙"
],
mymrtlng: [
"꧰",
"꧱",
"꧲",
"꧳",
"꧴",
"꧵",
"꧶",
"꧷",
"꧸",
"꧹"
],
newa: [
"𑑐",
"𑑑",
"𑑒",
"𑑓",
"𑑔",
"𑑕",
"𑑖",
"𑑗",
"𑑘",
"𑑙"
],
nkoo: [
"߀",
"߁",
"߂",
"߃",
"߄",
"߅",
"߆",
"߇",
"߈",
"߉"
],
olck: [
"᱐",
"᱑",
"᱒",
"᱓",
"᱔",
"᱕",
"᱖",
"᱗",
"᱘",
"᱙"
],
orya: [
"୦",
"୧",
"୨",
"୩",
"୪",
"୫",
"୬",
"୭",
"୮",
"୯"
],
osma: [
"𐒠",
"𐒡",
"𐒢",
"𐒣",
"𐒤",
"𐒥",
"𐒦",
"𐒧",
"𐒨",
"𐒩"
],
rohg: [
"𐴰",
"𐴱",
"𐴲",
"𐴳",
"𐴴",
"𐴵",
"𐴶",
"𐴷",
"𐴸",
"𐴹"
],
saur: [
"꣐",
"꣑",
"꣒",
"꣓",
"꣔",
"꣕",
"꣖",
"꣗",
"꣘",
"꣙"
],
segment: [
"🯰",
"🯱",
"🯲",
"🯳",
"🯴",
"🯵",
"🯶",
"🯷",
"🯸",
"🯹"
],
shrd: [
"𑇐",
"𑇑",
"𑇒",
"𑇓",
"𑇔",
"𑇕",
"𑇖",
"𑇗",
"𑇘",
"𑇙"
],
sind: [
"𑋰",
"𑋱",
"𑋲",
"𑋳",
"𑋴",
"𑋵",
"𑋶",
"𑋷",
"𑋸",
"𑋹"
],
sinh: [
"෦",
"෧",
"෨",
"෩",
"෪",
"෫",
"෬",
"෭",
"෮",
"෯"
],
sora: [
"𑃰",
"𑃱",
"𑃲",
"𑃳",
"𑃴",
"𑃵",
"𑃶",
"𑃷",
"𑃸",
"𑃹"
],
sund: [
"᮰",
"᮱",
"᮲",
"᮳",
"᮴",
"᮵",
"᮶",
"᮷",
"᮸",
"᮹"
],
takr: [
"𑛀",
"𑛁",
"𑛂",
"𑛃",
"𑛄",
"𑛅",
"𑛆",
"𑛇",
"𑛈",
"𑛉"
],
talu: [
"᧐",
"᧑",
"᧒",
"᧓",
"᧔",
"᧕",
"᧖",
"᧗",
"᧘",
"᧙"
],
tamldec: [
"௦",
"௧",
"௨",
"௩",
"௪",
"௫",
"௬",
"௭",
"௮",
"௯"
],
telu: [
"౦",
"౧",
"౨",
"౩",
"౪",
"౫",
"౬",
"౭",
"౮",
"౯"
],
thai: [
"๐",
"๑",
"๒",
"๓",
"๔",
"๕",
"๖",
"๗",
"๘",
"๙"
],
tibt: [
"༠",
"༡",
"༢",
"༣",
"༤",
"༥",
"༦",
"༧",
"༨",
"༩"
],
tirh: [
"𑓐",
"𑓑",
"𑓒",
"𑓓",
"𑓔",
"𑓕",
"𑓖",
"𑓗",
"𑓘",
"𑓙"
],
vaii: [
"ᘠ",
"ᘡ",
"ᘢ",
"ᘣ",
"ᘤ",
"ᘥ",
"ᘦ",
"ᘧ",
"ᘨ",
"ᘩ"
],
wara: [
"𑣠",
"𑣡",
"𑣢",
"𑣣",
"𑣤",
"𑣥",
"𑣦",
"𑣧",
"𑣨",
"𑣩"
],
wcho: [
"𞋰",
"𞋱",
"𞋲",
"𞋳",
"𞋴",
"𞋵",
"𞋶",
"𞋷",
"𞋸",
"𞋹"
]
};

@@ -1,24 +0,28 @@

import { Decimal } from 'decimal.js';
import { NumberFormatLocaleInternalData, NumberFormatOptionsCompactDisplay, NumberFormatOptionsCurrencyDisplay, NumberFormatOptionsCurrencySign, NumberFormatOptionsNotation, NumberFormatOptionsStyle, NumberFormatOptionsUnitDisplay, NumberFormatPart, RoundingModeType, UseGroupingType } from '../types/number.js';
import { Decimal } from "decimal.js";
import { type NumberFormatLocaleInternalData, type NumberFormatOptionsCompactDisplay, type NumberFormatOptionsCurrencyDisplay, type NumberFormatOptionsCurrencySign, type NumberFormatOptionsNotation, type NumberFormatOptionsStyle, type NumberFormatOptionsUnitDisplay, type NumberFormatPart, type RoundingModeType, type UseGroupingType } from "../types/number.js";
interface NumberResult {
formattedString: string;
roundedNumber: Decimal;
sign: -1 | 0 | 1;
exponent: number;
magnitude: number;
formattedString: string;
roundedNumber: Decimal;
sign: -1 | 0 | 1;
// Example: 100K has exponent 3 and magnitude 5.
exponent: number;
magnitude: number;
}
export default function formatToParts(numberResult: NumberResult, data: NumberFormatLocaleInternalData, pl: Intl.PluralRules, options: {
numberingSystem: string;
useGrouping?: UseGroupingType;
style: NumberFormatOptionsStyle;
notation: NumberFormatOptionsNotation;
compactDisplay?: NumberFormatOptionsCompactDisplay;
currency?: string;
currencyDisplay?: NumberFormatOptionsCurrencyDisplay;
currencySign?: NumberFormatOptionsCurrencySign;
unit?: string;
unitDisplay?: NumberFormatOptionsUnitDisplay;
roundingIncrement: number;
roundingMode: RoundingModeType;
numberingSystem: string;
useGrouping?: UseGroupingType;
style: NumberFormatOptionsStyle;
// Notation
notation: NumberFormatOptionsNotation;
// Compact notation
compactDisplay?: NumberFormatOptionsCompactDisplay;
// Currency
currency?: string;
currencyDisplay?: NumberFormatOptionsCurrencyDisplay;
currencySign?: NumberFormatOptionsCurrencySign;
// Unit
unit?: string;
unitDisplay?: NumberFormatOptionsUnitDisplay;
roundingIncrement: number;
roundingMode: RoundingModeType;
}): NumberFormatPart[];
export {};

@@ -1,392 +0,410 @@

import { Decimal } from 'decimal.js';
import { S_UNICODE_REGEX } from '../regex.generated.js';
import { getPowerOf10 } from './decimal-cache.js';
import { digitMapping } from './digit-mapping.generated.js';
import { GetUnsignedRoundingMode } from './GetUnsignedRoundingMode.js';
import { ToRawFixed } from './ToRawFixed.js';
import { Decimal } from "decimal.js";
import { S_UNICODE_REGEX } from "../regex.generated.js";
import "../types/number.js";
import { getPowerOf10 } from "./decimal-cache.js";
import "../types/plural-rules.js";
import { digitMapping } from "./digit-mapping.generated.js";
import { GetUnsignedRoundingMode } from "./GetUnsignedRoundingMode.js";
import { ToRawFixed } from "./ToRawFixed.js";
// This is from: unicode-12.1.0/General_Category/Symbol/regex.js
// IE11 does not support unicode flag, otherwise this is just /\p{S}/u.
// /^\p{S}/u
var CARET_S_UNICODE_REGEX = new RegExp("^".concat(S_UNICODE_REGEX.source));
const CARET_S_UNICODE_REGEX = new RegExp(`^${S_UNICODE_REGEX.source}`);
// /\p{S}$/u
var S_DOLLAR_UNICODE_REGEX = new RegExp("".concat(S_UNICODE_REGEX.source, "$"));
var CLDR_NUMBER_PATTERN = /[#0](?:[.,][#0]+)*/g;
const S_DOLLAR_UNICODE_REGEX = new RegExp(`${S_UNICODE_REGEX.source}$`);
const CLDR_NUMBER_PATTERN = /[#0](?:[.,][#0]+)*/g;
export default function formatToParts(numberResult, data, pl, options) {
var _a;
var sign = numberResult.sign, exponent = numberResult.exponent, magnitude = numberResult.magnitude;
var notation = options.notation, style = options.style, numberingSystem = options.numberingSystem;
var defaultNumberingSystem = data.numbers.nu[0];
// #region Part 1: partition and interpolate the CLDR number pattern.
// ----------------------------------------------------------
var compactNumberPattern = null;
if (notation === 'compact' && magnitude) {
compactNumberPattern = getCompactDisplayPattern(numberResult, pl, data, style, options.compactDisplay, options.currencyDisplay, numberingSystem);
}
// This is used multiple times
var nonNameCurrencyPart;
if (style === 'currency' && options.currencyDisplay !== 'name') {
var byCurrencyDisplay = data.currencies[options.currency];
if (byCurrencyDisplay) {
switch (options.currencyDisplay) {
case 'code':
nonNameCurrencyPart = options.currency;
break;
case 'symbol':
nonNameCurrencyPart = byCurrencyDisplay.symbol;
break;
default:
nonNameCurrencyPart = byCurrencyDisplay.narrow;
break;
}
}
else {
// Fallback for unknown currency
nonNameCurrencyPart = options.currency;
}
}
var numberPattern;
if (!compactNumberPattern) {
// Note: if the style is unit, or is currency and the currency display is name,
// its unit parts will be interpolated in part 2. So here we can fallback to decimal.
if (style === 'decimal' ||
style === 'unit' ||
(style === 'currency' && options.currencyDisplay === 'name')) {
// Shortcut for decimal
var decimalData = data.numbers.decimal[numberingSystem] ||
data.numbers.decimal[defaultNumberingSystem];
numberPattern = getPatternForSign(decimalData.standard, sign);
}
else if (style === 'currency') {
var currencyData = data.numbers.currency[numberingSystem] ||
data.numbers.currency[defaultNumberingSystem];
// We replace number pattern part with `0` for easier postprocessing.
numberPattern = getPatternForSign(currencyData[options.currencySign], sign);
}
else {
// percent
var percentPattern = data.numbers.percent[numberingSystem] ||
data.numbers.percent[defaultNumberingSystem];
numberPattern = getPatternForSign(percentPattern, sign);
}
}
else {
numberPattern = compactNumberPattern;
}
// Extract the decimal number pattern string. It looks like "#,##0,00", which will later be
// used to infer decimal group sizes.
var decimalNumberPattern = CLDR_NUMBER_PATTERN.exec(numberPattern)[0];
// Now we start to substitute patterns
// 1. replace strings like `0` and `#,##0.00` with `{0}`
// 2. unquote characters (invariant: the quoted characters does not contain the special tokens)
numberPattern = numberPattern
.replace(CLDR_NUMBER_PATTERN, '{0}')
.replace(/'(.)'/g, '$1');
// Handle currency spacing (both compact and non-compact).
if (style === 'currency' && options.currencyDisplay !== 'name') {
var currencyData = data.numbers.currency[numberingSystem] ||
data.numbers.currency[defaultNumberingSystem];
// See `currencySpacing` substitution rule in TR-35.
// Here we always assume the currencyMatch is "[:^S:]" and surroundingMatch is "[:digit:]".
//
// Example 1: for pattern "#,##0.00¤" with symbol "US$", we replace "¤" with the symbol,
// but insert an extra non-break space before the symbol, because "[:^S:]" matches "U" in
// "US$" and "[:digit:]" matches the latn numbering system digits.
//
// Example 2: for pattern "¤#,##0.00" with symbol "US$", there is no spacing between symbol
// and number, because `$` does not match "[:^S:]".
//
// Implementation note: here we do the best effort to infer the insertion.
// We also assume that `beforeInsertBetween` and `afterInsertBetween` will never be `;`.
var afterCurrency = currencyData.currencySpacing.afterInsertBetween;
if (afterCurrency && !S_DOLLAR_UNICODE_REGEX.test(nonNameCurrencyPart)) {
numberPattern = numberPattern.replace('¤{0}', "\u00A4".concat(afterCurrency, "{0}"));
}
var beforeCurrency = currencyData.currencySpacing.beforeInsertBetween;
if (beforeCurrency && !CARET_S_UNICODE_REGEX.test(nonNameCurrencyPart)) {
numberPattern = numberPattern.replace('{0}¤', "{0}".concat(beforeCurrency, "\u00A4"));
}
}
// The following tokens are special: `{0}`, `¤`, `%`, `-`, `+`, `{c:...}.
var numberPatternParts = numberPattern.split(/({c:[^}]+}|\{0\}|[¤%\-+])/g);
var numberParts = [];
var symbols = data.numbers.symbols[numberingSystem] ||
data.numbers.symbols[defaultNumberingSystem];
for (var _i = 0, numberPatternParts_1 = numberPatternParts; _i < numberPatternParts_1.length; _i++) {
var part = numberPatternParts_1[_i];
if (!part) {
continue;
}
switch (part) {
case '{0}': {
// We only need to handle scientific and engineering notation here.
numberParts.push.apply(numberParts, partitionNumberIntoParts(symbols, numberResult, notation, exponent, numberingSystem,
// If compact number pattern exists, do not insert group separators.
!compactNumberPattern && ((_a = options.useGrouping) !== null && _a !== void 0 ? _a : true), decimalNumberPattern, style, options.roundingIncrement, GetUnsignedRoundingMode(options.roundingMode, sign === -1)));
break;
}
case '-':
numberParts.push({ type: 'minusSign', value: symbols.minusSign });
break;
case '+':
numberParts.push({ type: 'plusSign', value: symbols.plusSign });
break;
case '%':
numberParts.push({ type: 'percentSign', value: symbols.percentSign });
break;
case '¤':
// Computed above when handling currency spacing.
numberParts.push({ type: 'currency', value: nonNameCurrencyPart });
break;
default:
if (part.startsWith('{c:')) {
numberParts.push({
type: 'compact',
value: part.substring(3, part.length - 1),
});
}
else {
// literal
numberParts.push({ type: 'literal', value: part });
}
break;
}
}
// #endregion
// #region Part 2: interpolate unit pattern if necessary.
// ----------------------------------------------
switch (style) {
case 'currency': {
// `currencyDisplay: 'name'` has similar pattern handling as units.
if (options.currencyDisplay === 'name') {
var unitPattern = (data.numbers.currency[numberingSystem] ||
data.numbers.currency[defaultNumberingSystem]).unitPattern;
// Select plural
var unitName = void 0;
var currencyNameData = data.currencies[options.currency];
if (currencyNameData) {
unitName = selectPlural(pl, numberResult.roundedNumber.times(getPowerOf10(exponent)).toNumber(), currencyNameData.displayName);
}
else {
// Fallback for unknown currency
unitName = options.currency;
}
// Do {0} and {1} substitution
var unitPatternParts = unitPattern.split(/(\{[01]\})/g);
var result = [];
for (var _b = 0, unitPatternParts_1 = unitPatternParts; _b < unitPatternParts_1.length; _b++) {
var part = unitPatternParts_1[_b];
switch (part) {
case '{0}':
result.push.apply(result, numberParts);
break;
case '{1}':
result.push({ type: 'currency', value: unitName });
break;
default:
if (part) {
result.push({ type: 'literal', value: part });
}
break;
}
}
return result;
}
else {
return numberParts;
}
}
case 'unit': {
var unit = options.unit, unitDisplay = options.unitDisplay;
var unitData = data.units.simple[unit];
var unitPattern = void 0;
if (unitData) {
// Simple unit pattern
unitPattern = selectPlural(pl, numberResult.roundedNumber.times(getPowerOf10(exponent)).toNumber(), data.units.simple[unit][unitDisplay]);
}
else {
// See: http://unicode.org/reports/tr35/tr35-general.html#perUnitPatterns
// If cannot find unit in the simple pattern, it must be "per" compound pattern.
// Implementation note: we are not following TR-35 here because we need to format to parts!
var _c = unit.split('-per-'), numeratorUnit = _c[0], denominatorUnit = _c[1];
unitData = data.units.simple[numeratorUnit];
var numeratorUnitPattern = selectPlural(pl, numberResult.roundedNumber.times(getPowerOf10(exponent)).toNumber(), data.units.simple[numeratorUnit][unitDisplay]);
var perUnitPattern = data.units.simple[denominatorUnit].perUnit[unitDisplay];
if (perUnitPattern) {
// perUnitPattern exists, combine it with numeratorUnitPattern
unitPattern = perUnitPattern.replace('{0}', numeratorUnitPattern);
}
else {
// get compoundUnit pattern (e.g. "{0} per {1}"), repalce {0} with numerator pattern and {1} with
// the denominator pattern in singular form.
var perPattern = data.units.compound.per[unitDisplay];
var denominatorPattern = selectPlural(pl, 1, data.units.simple[denominatorUnit][unitDisplay]);
unitPattern = unitPattern = perPattern
.replace('{0}', numeratorUnitPattern)
.replace('{1}', denominatorPattern.replace('{0}', ''));
}
}
var result = [];
// We need spacing around "{0}" because they are not treated as "unit" parts, but "literal".
for (var _d = 0, _e = unitPattern.split(/(\s*\{0\}\s*)/); _d < _e.length; _d++) {
var part = _e[_d];
var interpolateMatch = /^(\s*)\{0\}(\s*)$/.exec(part);
if (interpolateMatch) {
// Space before "{0}"
if (interpolateMatch[1]) {
result.push({ type: 'literal', value: interpolateMatch[1] });
}
// "{0}" itself
result.push.apply(result, numberParts);
// Space after "{0}"
if (interpolateMatch[2]) {
result.push({ type: 'literal', value: interpolateMatch[2] });
}
}
else if (part) {
result.push({ type: 'unit', value: part });
}
}
return result;
}
default:
return numberParts;
}
// #endregion
const { sign, exponent, magnitude } = numberResult;
const { notation, style, numberingSystem } = options;
const defaultNumberingSystem = data.numbers.nu[0];
// #region Part 1: partition and interpolate the CLDR number pattern.
// ----------------------------------------------------------
let compactNumberPattern = null;
if (notation === "compact" && magnitude) {
compactNumberPattern = getCompactDisplayPattern(numberResult, pl, data, style, options.compactDisplay, options.currencyDisplay, numberingSystem);
}
// This is used multiple times
let nonNameCurrencyPart;
if (style === "currency" && options.currencyDisplay !== "name") {
const byCurrencyDisplay = data.currencies[options.currency];
if (byCurrencyDisplay) {
switch (options.currencyDisplay) {
case "code":
nonNameCurrencyPart = options.currency;
break;
case "symbol":
nonNameCurrencyPart = byCurrencyDisplay.symbol;
break;
default:
nonNameCurrencyPart = byCurrencyDisplay.narrow;
break;
}
} else {
// Fallback for unknown currency
nonNameCurrencyPart = options.currency;
}
}
let numberPattern;
if (!compactNumberPattern) {
// Note: if the style is unit, or is currency and the currency display is name,
// its unit parts will be interpolated in part 2. So here we can fallback to decimal.
if (style === "decimal" || style === "unit" || style === "currency" && options.currencyDisplay === "name") {
// Shortcut for decimal
const decimalData = data.numbers.decimal[numberingSystem] || data.numbers.decimal[defaultNumberingSystem];
numberPattern = getPatternForSign(decimalData.standard, sign);
} else if (style === "currency") {
const currencyData = data.numbers.currency[numberingSystem] || data.numbers.currency[defaultNumberingSystem];
// We replace number pattern part with `0` for easier postprocessing.
numberPattern = getPatternForSign(currencyData[options.currencySign], sign);
} else {
// percent
const percentPattern = data.numbers.percent[numberingSystem] || data.numbers.percent[defaultNumberingSystem];
numberPattern = getPatternForSign(percentPattern, sign);
}
} else {
numberPattern = compactNumberPattern;
}
// Extract the decimal number pattern string. It looks like "#,##0,00", which will later be
// used to infer decimal group sizes.
const decimalNumberPattern = CLDR_NUMBER_PATTERN.exec(numberPattern)[0];
// Now we start to substitute patterns
// 1. replace strings like `0` and `#,##0.00` with `{0}`
// 2. unquote characters (invariant: the quoted characters does not contain the special tokens)
numberPattern = numberPattern.replace(CLDR_NUMBER_PATTERN, "{0}").replace(/'(.)'/g, "$1");
// Handle currency spacing (both compact and non-compact).
if (style === "currency" && options.currencyDisplay !== "name") {
const currencyData = data.numbers.currency[numberingSystem] || data.numbers.currency[defaultNumberingSystem];
// See `currencySpacing` substitution rule in TR-35.
// Here we always assume the currencyMatch is "[:^S:]" and surroundingMatch is "[:digit:]".
//
// Example 1: for pattern "#,##0.00¤" with symbol "US$", we replace "¤" with the symbol,
// but insert an extra non-break space before the symbol, because "[:^S:]" matches "U" in
// "US$" and "[:digit:]" matches the latn numbering system digits.
//
// Example 2: for pattern "¤#,##0.00" with symbol "US$", there is no spacing between symbol
// and number, because `$` does not match "[:^S:]".
//
// Implementation note: here we do the best effort to infer the insertion.
// We also assume that `beforeInsertBetween` and `afterInsertBetween` will never be `;`.
const afterCurrency = currencyData.currencySpacing.afterInsertBetween;
if (afterCurrency && !S_DOLLAR_UNICODE_REGEX.test(nonNameCurrencyPart)) {
numberPattern = numberPattern.replace("¤{0}", `¤${afterCurrency}{0}`);
}
const beforeCurrency = currencyData.currencySpacing.beforeInsertBetween;
if (beforeCurrency && !CARET_S_UNICODE_REGEX.test(nonNameCurrencyPart)) {
numberPattern = numberPattern.replace("{0}¤", `{0}${beforeCurrency}¤`);
}
}
// The following tokens are special: `{0}`, `¤`, `%`, `-`, `+`, `{c:...}.
const numberPatternParts = numberPattern.split(/({c:[^}]+}|\{0\}|[¤%\-+])/g);
const numberParts = [];
const symbols = data.numbers.symbols[numberingSystem] || data.numbers.symbols[defaultNumberingSystem];
for (const part of numberPatternParts) {
if (!part) {
continue;
}
switch (part) {
case "{0}": {
// We only need to handle scientific and engineering notation here.
numberParts.push(...partitionNumberIntoParts(
symbols,
numberResult,
notation,
exponent,
numberingSystem,
// If compact number pattern exists, do not insert group separators.
!compactNumberPattern && (options.useGrouping ?? true),
decimalNumberPattern,
style,
options.roundingIncrement,
GetUnsignedRoundingMode(options.roundingMode, sign === -1)
));
break;
}
case "-":
numberParts.push({
type: "minusSign",
value: symbols.minusSign
});
break;
case "+":
numberParts.push({
type: "plusSign",
value: symbols.plusSign
});
break;
case "%":
numberParts.push({
type: "percentSign",
value: symbols.percentSign
});
break;
case "¤":
// Computed above when handling currency spacing.
numberParts.push({
type: "currency",
value: nonNameCurrencyPart
});
break;
default:
if (part.startsWith("{c:")) {
numberParts.push({
type: "compact",
value: part.substring(3, part.length - 1)
});
} else {
// literal
numberParts.push({
type: "literal",
value: part
});
}
break;
}
}
// #endregion
// #region Part 2: interpolate unit pattern if necessary.
// ----------------------------------------------
switch (style) {
case "currency": {
// `currencyDisplay: 'name'` has similar pattern handling as units.
if (options.currencyDisplay === "name") {
const unitPattern = (data.numbers.currency[numberingSystem] || data.numbers.currency[defaultNumberingSystem]).unitPattern;
// Select plural
let unitName;
const currencyNameData = data.currencies[options.currency];
if (currencyNameData) {
unitName = selectPlural(pl, numberResult.roundedNumber.times(getPowerOf10(exponent)).toNumber(), currencyNameData.displayName);
} else {
// Fallback for unknown currency
unitName = options.currency;
}
// Do {0} and {1} substitution
const unitPatternParts = unitPattern.split(/(\{[01]\})/g);
const result = [];
for (const part of unitPatternParts) {
switch (part) {
case "{0}":
result.push(...numberParts);
break;
case "{1}":
result.push({
type: "currency",
value: unitName
});
break;
default:
if (part) {
result.push({
type: "literal",
value: part
});
}
break;
}
}
return result;
} else {
return numberParts;
}
}
case "unit": {
const { unit, unitDisplay } = options;
let unitData = data.units.simple[unit];
let unitPattern;
if (unitData) {
// Simple unit pattern
unitPattern = selectPlural(pl, numberResult.roundedNumber.times(getPowerOf10(exponent)).toNumber(), data.units.simple[unit][unitDisplay]);
} else {
// See: http://unicode.org/reports/tr35/tr35-general.html#perUnitPatterns
// If cannot find unit in the simple pattern, it must be "per" compound pattern.
// Implementation note: we are not following TR-35 here because we need to format to parts!
const [numeratorUnit, denominatorUnit] = unit.split("-per-");
unitData = data.units.simple[numeratorUnit];
const numeratorUnitPattern = selectPlural(pl, numberResult.roundedNumber.times(getPowerOf10(exponent)).toNumber(), data.units.simple[numeratorUnit][unitDisplay]);
const perUnitPattern = data.units.simple[denominatorUnit].perUnit[unitDisplay];
if (perUnitPattern) {
// perUnitPattern exists, combine it with numeratorUnitPattern
unitPattern = perUnitPattern.replace("{0}", numeratorUnitPattern);
} else {
// get compoundUnit pattern (e.g. "{0} per {1}"), repalce {0} with numerator pattern and {1} with
// the denominator pattern in singular form.
const perPattern = data.units.compound.per[unitDisplay];
const denominatorPattern = selectPlural(pl, 1, data.units.simple[denominatorUnit][unitDisplay]);
unitPattern = unitPattern = perPattern.replace("{0}", numeratorUnitPattern).replace("{1}", denominatorPattern.replace("{0}", ""));
}
}
const result = [];
// We need spacing around "{0}" because they are not treated as "unit" parts, but "literal".
for (const part of unitPattern.split(/(\s*\{0\}\s*)/)) {
const interpolateMatch = /^(\s*)\{0\}(\s*)$/.exec(part);
if (interpolateMatch) {
// Space before "{0}"
if (interpolateMatch[1]) {
result.push({
type: "literal",
value: interpolateMatch[1]
});
}
// "{0}" itself
result.push(...numberParts);
// Space after "{0}"
if (interpolateMatch[2]) {
result.push({
type: "literal",
value: interpolateMatch[2]
});
}
} else if (part) {
result.push({
type: "unit",
value: part
});
}
}
return result;
}
default: return numberParts;
}
// #endregion
}
// A subset of https://tc39.es/ecma402/#sec-partitionnotationsubpattern
// Plus the exponent parts handling.
function partitionNumberIntoParts(symbols, numberResult, notation, exponent, numberingSystem, useGrouping,
/**
* This is the decimal number pattern without signs or symbols.
* It is used to infer the group size when `useGrouping` is true.
*
* A typical value looks like "#,##0.00" (primary group size is 3).
* Some locales like Hindi has secondary group size of 2 (e.g. "#,##,##0.00").
*/
decimalNumberPattern, style, roundingIncrement, unsignedRoundingMode) {
var result = [];
// eslint-disable-next-line prefer-const
var n = numberResult.formattedString, x = numberResult.roundedNumber;
if (x.isNaN()) {
return [{ type: 'nan', value: n }];
}
else if (!x.isFinite()) {
return [{ type: 'infinity', value: n }];
}
var digitReplacementTable = digitMapping[numberingSystem];
if (digitReplacementTable) {
n = n.replace(/\d/g, function (digit) { return digitReplacementTable[+digit] || digit; });
}
// TODO: Else use an implementation dependent algorithm to map n to the appropriate
// representation of n in the given numbering system.
var decimalSepIndex = n.indexOf('.');
var integer;
var fraction;
if (decimalSepIndex > 0) {
integer = n.slice(0, decimalSepIndex);
fraction = n.slice(decimalSepIndex + 1);
}
else {
integer = n;
}
// #region Grouping integer digits
// The weird compact and x >= 10000 check is to ensure consistency with Node.js and Chrome.
// Note that `de` does not have compact form for thousands, but Node.js does not insert grouping separator
// unless the rounded number is greater than 10000:
// NumberFormat('de', {notation: 'compact', compactDisplay: 'short'}).format(1234) //=> "1234"
// NumberFormat('de').format(1234) //=> "1.234"
var shouldUseGrouping = false;
if (useGrouping === 'always') {
shouldUseGrouping = true;
}
else if (useGrouping === 'min2') {
shouldUseGrouping = x.greaterThanOrEqualTo(10000);
}
else if (useGrouping === 'auto' || useGrouping) {
shouldUseGrouping = notation !== 'compact' || x.greaterThanOrEqualTo(10000);
}
if (shouldUseGrouping) {
// a. Let groupSepSymbol be the implementation-, locale-, and numbering system-dependent (ILND) String representing the grouping separator.
// For currency we should use `currencyGroup` instead of generic `group`
var groupSepSymbol = style === 'currency' && symbols.currencyGroup != null
? symbols.currencyGroup
: symbols.group;
var groups = [];
// > There may be two different grouping sizes: The primary grouping size used for the least
// > significant integer group, and the secondary grouping size used for more significant groups.
// > If a pattern contains multiple grouping separators, the interval between the last one and the
// > end of the integer defines the primary grouping size, and the interval between the last two
// > defines the secondary grouping size. All others are ignored.
var integerNumberPattern = decimalNumberPattern.split('.')[0];
var patternGroups = integerNumberPattern.split(',');
var primaryGroupingSize = 3;
var secondaryGroupingSize = 3;
if (patternGroups.length > 1) {
primaryGroupingSize = patternGroups[patternGroups.length - 1].length;
}
if (patternGroups.length > 2) {
secondaryGroupingSize = patternGroups[patternGroups.length - 2].length;
}
var i = integer.length - primaryGroupingSize;
if (i > 0) {
// Slice the least significant integer group
groups.push(integer.slice(i, i + primaryGroupingSize));
// Then iteratively push the more signicant groups
// TODO: handle surrogate pairs in some numbering system digits
for (i -= secondaryGroupingSize; i > 0; i -= secondaryGroupingSize) {
groups.push(integer.slice(i, i + secondaryGroupingSize));
}
groups.push(integer.slice(0, i + secondaryGroupingSize));
}
else {
groups.push(integer);
}
while (groups.length > 0) {
var integerGroup = groups.pop();
result.push({ type: 'integer', value: integerGroup });
if (groups.length > 0) {
result.push({ type: 'group', value: groupSepSymbol });
}
}
}
else {
result.push({ type: 'integer', value: integer });
}
// #endregion
if (fraction !== undefined) {
var decimalSepSymbol = style === 'currency' && symbols.currencyDecimal != null
? symbols.currencyDecimal
: symbols.decimal;
result.push({ type: 'decimal', value: decimalSepSymbol }, { type: 'fraction', value: fraction });
}
if ((notation === 'scientific' || notation === 'engineering') &&
x.isFinite()) {
result.push({ type: 'exponentSeparator', value: symbols.exponential });
if (exponent < 0) {
result.push({ type: 'exponentMinusSign', value: symbols.minusSign });
exponent = -exponent;
}
var exponentResult = ToRawFixed(new Decimal(exponent), 0, 0, roundingIncrement, unsignedRoundingMode);
result.push({
type: 'exponentInteger',
value: exponentResult.formattedString,
});
}
return result;
function partitionNumberIntoParts(symbols, numberResult, notation, exponent, numberingSystem, useGrouping, decimalNumberPattern, style, roundingIncrement, unsignedRoundingMode) {
const result = [];
// eslint-disable-next-line prefer-const
let { formattedString: n, roundedNumber: x } = numberResult;
if (x.isNaN()) {
return [{
type: "nan",
value: n
}];
} else if (!x.isFinite()) {
return [{
type: "infinity",
value: n
}];
}
const digitReplacementTable = digitMapping[numberingSystem];
if (digitReplacementTable) {
n = n.replace(/\d/g, (digit) => digitReplacementTable[+digit] || digit);
}
// TODO: Else use an implementation dependent algorithm to map n to the appropriate
// representation of n in the given numbering system.
const decimalSepIndex = n.indexOf(".");
let integer;
let fraction;
if (decimalSepIndex > 0) {
integer = n.slice(0, decimalSepIndex);
fraction = n.slice(decimalSepIndex + 1);
} else {
integer = n;
}
// #region Grouping integer digits
// The weird compact and x >= 10000 check is to ensure consistency with Node.js and Chrome.
// Note that `de` does not have compact form for thousands, but Node.js does not insert grouping separator
// unless the rounded number is greater than 10000:
// NumberFormat('de', {notation: 'compact', compactDisplay: 'short'}).format(1234) //=> "1234"
// NumberFormat('de').format(1234) //=> "1.234"
let shouldUseGrouping = false;
if (useGrouping === "always") {
shouldUseGrouping = true;
} else if (useGrouping === "min2") {
shouldUseGrouping = x.greaterThanOrEqualTo(1e4);
} else if (useGrouping === "auto" || useGrouping) {
shouldUseGrouping = notation !== "compact" || x.greaterThanOrEqualTo(1e4);
}
if (shouldUseGrouping) {
// a. Let groupSepSymbol be the implementation-, locale-, and numbering system-dependent (ILND) String representing the grouping separator.
// For currency we should use `currencyGroup` instead of generic `group`
const groupSepSymbol = style === "currency" && symbols.currencyGroup != null ? symbols.currencyGroup : symbols.group;
const groups = [];
// > There may be two different grouping sizes: The primary grouping size used for the least
// > significant integer group, and the secondary grouping size used for more significant groups.
// > If a pattern contains multiple grouping separators, the interval between the last one and the
// > end of the integer defines the primary grouping size, and the interval between the last two
// > defines the secondary grouping size. All others are ignored.
const integerNumberPattern = decimalNumberPattern.split(".")[0];
const patternGroups = integerNumberPattern.split(",");
let primaryGroupingSize = 3;
let secondaryGroupingSize = 3;
if (patternGroups.length > 1) {
primaryGroupingSize = patternGroups[patternGroups.length - 1].length;
}
if (patternGroups.length > 2) {
secondaryGroupingSize = patternGroups[patternGroups.length - 2].length;
}
let i = integer.length - primaryGroupingSize;
if (i > 0) {
// Slice the least significant integer group
groups.push(integer.slice(i, i + primaryGroupingSize));
// Then iteratively push the more signicant groups
// TODO: handle surrogate pairs in some numbering system digits
for (i -= secondaryGroupingSize; i > 0; i -= secondaryGroupingSize) {
groups.push(integer.slice(i, i + secondaryGroupingSize));
}
groups.push(integer.slice(0, i + secondaryGroupingSize));
} else {
groups.push(integer);
}
while (groups.length > 0) {
const integerGroup = groups.pop();
result.push({
type: "integer",
value: integerGroup
});
if (groups.length > 0) {
result.push({
type: "group",
value: groupSepSymbol
});
}
}
} else {
result.push({
type: "integer",
value: integer
});
}
// #endregion
if (fraction !== undefined) {
const decimalSepSymbol = style === "currency" && symbols.currencyDecimal != null ? symbols.currencyDecimal : symbols.decimal;
result.push({
type: "decimal",
value: decimalSepSymbol
}, {
type: "fraction",
value: fraction
});
}
if ((notation === "scientific" || notation === "engineering") && x.isFinite()) {
result.push({
type: "exponentSeparator",
value: symbols.exponential
});
if (exponent < 0) {
result.push({
type: "exponentMinusSign",
value: symbols.minusSign
});
exponent = -exponent;
}
const exponentResult = ToRawFixed(new Decimal(exponent), 0, 0, roundingIncrement, unsignedRoundingMode);
result.push({
type: "exponentInteger",
value: exponentResult.formattedString
});
}
return result;
}
function getPatternForSign(pattern, sign) {
if (pattern.indexOf(';') < 0) {
pattern = "".concat(pattern, ";-").concat(pattern);
}
var _a = pattern.split(';'), zeroPattern = _a[0], negativePattern = _a[1];
switch (sign) {
case 0:
return zeroPattern;
case -1:
return negativePattern;
default:
return negativePattern.indexOf('-') >= 0
? negativePattern.replace(/-/g, '+')
: "+".concat(zeroPattern);
}
if (pattern.indexOf(";") < 0) {
pattern = `${pattern};-${pattern}`;
}
const [zeroPattern, negativePattern] = pattern.split(";");
switch (sign) {
case 0: return zeroPattern;
case -1: return negativePattern;
default: return negativePattern.indexOf("-") >= 0 ? negativePattern.replace(/-/g, "+") : `+${zeroPattern}`;
}
}

@@ -401,61 +419,51 @@ // Find the CLDR pattern for compact notation based on the magnitude of data and style.

function getCompactDisplayPattern(numberResult, pl, data, style, compactDisplay, currencyDisplay, numberingSystem) {
var _a, _b;
var roundedNumber = numberResult.roundedNumber, sign = numberResult.sign, magnitude = numberResult.magnitude;
var magnitudeKey = String(Math.pow(10, magnitude));
var defaultNumberingSystem = data.numbers.nu[0];
var pattern;
if (style === 'currency' && currencyDisplay !== 'name') {
var byNumberingSystem = data.numbers.currency;
var currencyData = byNumberingSystem[numberingSystem] ||
byNumberingSystem[defaultNumberingSystem];
// NOTE: compact notation ignores currencySign!
var compactPluralRules = (_a = currencyData.short) === null || _a === void 0 ? void 0 : _a[magnitudeKey];
// GH #4236: If magnitude exceeds available patterns, use the largest available
if (!compactPluralRules) {
var thresholds = Object.keys(currencyData.short || {});
if (thresholds.length > 0 &&
magnitudeKey > thresholds[thresholds.length - 1]) {
magnitudeKey = thresholds[thresholds.length - 1];
compactPluralRules = (_b = currencyData.short) === null || _b === void 0 ? void 0 : _b[magnitudeKey];
}
}
if (!compactPluralRules) {
return null;
}
pattern = selectPlural(pl, roundedNumber.toNumber(), compactPluralRules);
}
else {
var byNumberingSystem = data.numbers.decimal;
var byCompactDisplay = byNumberingSystem[numberingSystem] ||
byNumberingSystem[defaultNumberingSystem];
var compactPlaralRule = byCompactDisplay[compactDisplay][magnitudeKey];
// GH #4236: If magnitude exceeds available patterns, use the largest available
if (!compactPlaralRule) {
var thresholds = Object.keys(byCompactDisplay[compactDisplay]);
if (thresholds.length > 0 &&
magnitudeKey > thresholds[thresholds.length - 1]) {
magnitudeKey = thresholds[thresholds.length - 1];
compactPlaralRule = byCompactDisplay[compactDisplay][magnitudeKey];
}
}
if (!compactPlaralRule) {
return null;
}
pattern = selectPlural(pl, roundedNumber.toNumber(), compactPlaralRule);
}
// See https://unicode.org/reports/tr35/tr35-numbers.html#Compact_Number_Formats
// > If the value is precisely “0”, either explicit or defaulted, then the normal number format
// > pattern for that sort of object is supplied.
if (pattern === '0') {
return null;
}
pattern = getPatternForSign(pattern, sign)
// Extract compact literal from the pattern
.replace(/([^\s;\-+\d¤]+)/g, '{c:$1}')
// We replace one or more zeros with a single zero so it matches `CLDR_NUMBER_PATTERN`.
.replace(/0+/, '0');
return pattern;
const { roundedNumber, sign, magnitude } = numberResult;
let magnitudeKey = String(10 ** magnitude);
const defaultNumberingSystem = data.numbers.nu[0];
let pattern;
if (style === "currency" && currencyDisplay !== "name") {
const byNumberingSystem = data.numbers.currency;
const currencyData = byNumberingSystem[numberingSystem] || byNumberingSystem[defaultNumberingSystem];
// NOTE: compact notation ignores currencySign!
let compactPluralRules = currencyData.short?.[magnitudeKey];
// GH #4236: If magnitude exceeds available patterns, use the largest available
if (!compactPluralRules) {
const thresholds = Object.keys(currencyData.short || {});
if (thresholds.length > 0 && magnitudeKey > thresholds[thresholds.length - 1]) {
magnitudeKey = thresholds[thresholds.length - 1];
compactPluralRules = currencyData.short?.[magnitudeKey];
}
}
if (!compactPluralRules) {
return null;
}
pattern = selectPlural(pl, roundedNumber.toNumber(), compactPluralRules);
} else {
const byNumberingSystem = data.numbers.decimal;
const byCompactDisplay = byNumberingSystem[numberingSystem] || byNumberingSystem[defaultNumberingSystem];
let compactPlaralRule = byCompactDisplay[compactDisplay][magnitudeKey];
// GH #4236: If magnitude exceeds available patterns, use the largest available
if (!compactPlaralRule) {
const thresholds = Object.keys(byCompactDisplay[compactDisplay]);
if (thresholds.length > 0 && magnitudeKey > thresholds[thresholds.length - 1]) {
magnitudeKey = thresholds[thresholds.length - 1];
compactPlaralRule = byCompactDisplay[compactDisplay][magnitudeKey];
}
}
if (!compactPlaralRule) {
return null;
}
pattern = selectPlural(pl, roundedNumber.toNumber(), compactPlaralRule);
}
// See https://unicode.org/reports/tr35/tr35-numbers.html#Compact_Number_Formats
// > If the value is precisely “0”, either explicit or defaulted, then the normal number format
// > pattern for that sort of object is supplied.
if (pattern === "0") {
return null;
}
pattern = getPatternForSign(pattern, sign).replace(/([^\s;\-+\d¤]+)/g, "{c:$1}").replace(/0+/, "0");
return pattern;
}
function selectPlural(pl, x, rules) {
return rules[pl.select(x)] || rules.other;
return rules[pl.select(x)] || rules.other;
}

@@ -1,5 +0,5 @@

import { NumberFormatInternal, NumberFormatPart } from '../types/number.js';
import { type NumberFormatInternal, type NumberFormatPart } from "../types/number.js";
/**
* https://tc39.es/ecma402/#sec-formatapproximately
*/
* https://tc39.es/ecma402/#sec-formatapproximately
*/
export declare function FormatApproximately(internalSlots: NumberFormatInternal, result: NumberFormatPart[]): NumberFormatPart[];

@@ -0,9 +1,13 @@

import "../types/number.js";
/**
* https://tc39.es/ecma402/#sec-formatapproximately
*/
* https://tc39.es/ecma402/#sec-formatapproximately
*/
export function FormatApproximately(internalSlots, result) {
var symbols = internalSlots.dataLocaleData.numbers.symbols[internalSlots.numberingSystem];
var approximatelySign = symbols.approximatelySign;
result.push({ type: 'approximatelySign', value: approximatelySign });
return result;
const symbols = internalSlots.dataLocaleData.numbers.symbols[internalSlots.numberingSystem];
const approximatelySign = symbols.approximatelySign;
result.push({
type: "approximatelySign",
value: approximatelySign
});
return result;
}

@@ -1,3 +0,3 @@

import { Decimal } from 'decimal.js';
import { NumberFormatInternal } from '../types/number.js';
import type { Decimal } from "decimal.js";
import { type NumberFormatInternal } from "../types/number.js";
export declare function FormatNumeric(internalSlots: NumberFormatInternal, x: Decimal): string;

@@ -1,5 +0,6 @@

import { PartitionNumberPattern } from './PartitionNumberPattern.js';
import "../types/number.js";
import { PartitionNumberPattern } from "./PartitionNumberPattern.js";
export function FormatNumeric(internalSlots, x) {
var parts = PartitionNumberPattern(internalSlots, x);
return parts.map(function (p) { return p.value; }).join('');
const parts = PartitionNumberPattern(internalSlots, x);
return parts.map((p) => p.value).join("");
}

@@ -1,8 +0,8 @@

import { Decimal } from 'decimal.js';
import { NumberFormatInternal } from '../types/number.js';
import type { Decimal } from "decimal.js";
import { type NumberFormatInternal } from "../types/number.js";
/**
* https://tc39.es/ecma402/#sec-formatnumericrange
*/
export declare function FormatNumericRange(numberFormat: Intl.NumberFormat, x: Decimal, y: Decimal, { getInternalSlots, }: {
getInternalSlots(nf: Intl.NumberFormat): NumberFormatInternal;
* https://tc39.es/ecma402/#sec-formatnumericrange
*/
export declare function FormatNumericRange(numberFormat: Intl.NumberFormat, x: Decimal, y: Decimal, { getInternalSlots }: {
getInternalSlots(nf: Intl.NumberFormat): NumberFormatInternal;
}): string;

@@ -1,11 +0,9 @@

import { PartitionNumberRangePattern } from './PartitionNumberRangePattern.js';
import "../types/number.js";
import { PartitionNumberRangePattern } from "./PartitionNumberRangePattern.js";
/**
* https://tc39.es/ecma402/#sec-formatnumericrange
*/
export function FormatNumericRange(numberFormat, x, y, _a) {
var getInternalSlots = _a.getInternalSlots;
var parts = PartitionNumberRangePattern(numberFormat, x, y, {
getInternalSlots: getInternalSlots,
});
return parts.map(function (part) { return part.value; }).join('');
* https://tc39.es/ecma402/#sec-formatnumericrange
*/
export function FormatNumericRange(numberFormat, x, y, { getInternalSlots }) {
const parts = PartitionNumberRangePattern(numberFormat, x, y, { getInternalSlots });
return parts.map((part) => part.value).join("");
}

@@ -1,8 +0,8 @@

import { Decimal } from 'decimal.js';
import { NumberFormatInternal, NumberRangeToParts } from '../types/number.js';
import type { Decimal } from "decimal.js";
import { type NumberFormatInternal, type NumberRangeToParts } from "../types/number.js";
/**
* https://tc39.es/ecma402/#sec-formatnumericrangetoparts
*/
export declare function FormatNumericRangeToParts(numberFormat: Intl.NumberFormat, x: Decimal, y: Decimal, { getInternalSlots, }: {
getInternalSlots(nf: Intl.NumberFormat): NumberFormatInternal;
* https://tc39.es/ecma402/#sec-formatnumericrangetoparts
*/
export declare function FormatNumericRangeToParts(numberFormat: Intl.NumberFormat, x: Decimal, y: Decimal, { getInternalSlots }: {
getInternalSlots(nf: Intl.NumberFormat): NumberFormatInternal;
}): NumberRangeToParts[];

@@ -1,16 +0,14 @@

import { PartitionNumberRangePattern } from './PartitionNumberRangePattern.js';
import "../types/number.js";
import { PartitionNumberRangePattern } from "./PartitionNumberRangePattern.js";
/**
* https://tc39.es/ecma402/#sec-formatnumericrangetoparts
*/
export function FormatNumericRangeToParts(numberFormat, x, y, _a) {
var getInternalSlots = _a.getInternalSlots;
var parts = PartitionNumberRangePattern(numberFormat, x, y, {
getInternalSlots: getInternalSlots,
});
return parts.map(function (part, index) { return ({
type: part.type,
value: part.value,
source: part.source,
result: index.toString(),
}); });
* https://tc39.es/ecma402/#sec-formatnumericrangetoparts
*/
export function FormatNumericRangeToParts(numberFormat, x, y, { getInternalSlots }) {
const parts = PartitionNumberRangePattern(numberFormat, x, y, { getInternalSlots });
return parts.map((part, index) => ({
type: part.type,
value: part.value,
source: part.source,
result: index.toString()
}));
}

@@ -1,5 +0,5 @@

import { Decimal } from 'decimal.js';
import { NumberFormatInternal, NumberFormatPart } from '../types/number.js';
import type { Decimal } from "decimal.js";
import { type NumberFormatInternal, type NumberFormatPart } from "../types/number.js";
export declare function FormatNumericToParts(nf: Intl.NumberFormat, x: Decimal, implDetails: {
getInternalSlots(nf: Intl.NumberFormat): NumberFormatInternal;
getInternalSlots(nf: Intl.NumberFormat): NumberFormatInternal;
}): NumberFormatPart[];

@@ -1,14 +0,14 @@

import { ArrayCreate } from '../262.js';
import { PartitionNumberPattern } from './PartitionNumberPattern.js';
import { ArrayCreate } from "../262.js";
import "../types/number.js";
import { PartitionNumberPattern } from "./PartitionNumberPattern.js";
export function FormatNumericToParts(nf, x, implDetails) {
var parts = PartitionNumberPattern(implDetails.getInternalSlots(nf), x);
var result = ArrayCreate(0);
for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
var part = parts_1[_i];
result.push({
type: part.type,
value: part.value,
});
}
return result;
const parts = PartitionNumberPattern(implDetails.getInternalSlots(nf), x);
const result = ArrayCreate(0);
for (const part of parts) {
result.push({
type: part.type,
value: part.value
});
}
return result;
}

@@ -1,9 +0,9 @@

import { Decimal } from 'decimal.js';
import { NumberFormatDigitInternalSlots } from '../types/number.js';
import type { Decimal } from "decimal.js";
import { type NumberFormatDigitInternalSlots } from "../types/number.js";
/**
* https://tc39.es/ecma402/#sec-formatnumberstring
*/
export declare function FormatNumericToString(intlObject: Pick<NumberFormatDigitInternalSlots, 'roundingType' | 'minimumSignificantDigits' | 'maximumSignificantDigits' | 'minimumIntegerDigits' | 'minimumFractionDigits' | 'maximumFractionDigits' | 'roundingIncrement' | 'roundingMode' | 'trailingZeroDisplay'>, _x: Decimal): {
roundedNumber: Decimal;
formattedString: string;
* https://tc39.es/ecma402/#sec-formatnumberstring
*/
export declare function FormatNumericToString(intlObject: Pick<NumberFormatDigitInternalSlots, "roundingType" | "minimumSignificantDigits" | "maximumSignificantDigits" | "minimumIntegerDigits" | "minimumFractionDigits" | "maximumFractionDigits" | "roundingIncrement" | "roundingMode" | "trailingZeroDisplay">, _x: Decimal): {
roundedNumber: Decimal;
formattedString: string;
};

@@ -1,84 +0,82 @@

import { NEGATIVE_ZERO, ZERO } from '../constants.js';
import { invariant, repeat } from '../utils.js';
import { GetUnsignedRoundingMode } from './GetUnsignedRoundingMode.js';
import { ToRawFixed } from './ToRawFixed.js';
import { ToRawPrecision } from './ToRawPrecision.js';
import { NEGATIVE_ZERO, ZERO } from "../constants.js";
import "../types/number.js";
import { invariant, repeat } from "../utils.js";
import { GetUnsignedRoundingMode } from "./GetUnsignedRoundingMode.js";
import { ToRawFixed } from "./ToRawFixed.js";
import { ToRawPrecision } from "./ToRawPrecision.js";
/**
* https://tc39.es/ecma402/#sec-formatnumberstring
*/
* https://tc39.es/ecma402/#sec-formatnumberstring
*/
export function FormatNumericToString(intlObject, _x) {
var x = _x;
var sign;
// -0
if (x.isZero() && x.isNegative()) {
sign = 'negative';
x = ZERO;
}
else {
invariant(x.isFinite(), 'NumberFormatDigitInternalSlots value is not finite');
if (x.lessThan(0)) {
sign = 'negative';
}
else {
sign = 'positive';
}
if (sign === 'negative') {
x = x.negated();
}
}
var result;
var roundingType = intlObject.roundingType;
var unsignedRoundingMode = GetUnsignedRoundingMode(intlObject.roundingMode, sign === 'negative');
switch (roundingType) {
case 'significantDigits':
result = ToRawPrecision(x, intlObject.minimumSignificantDigits, intlObject.maximumSignificantDigits, unsignedRoundingMode);
break;
case 'fractionDigits':
result = ToRawFixed(x, intlObject.minimumFractionDigits, intlObject.maximumFractionDigits, intlObject.roundingIncrement, unsignedRoundingMode);
break;
default:
var sResult = ToRawPrecision(x, intlObject.minimumSignificantDigits, intlObject.maximumSignificantDigits, unsignedRoundingMode);
var fResult = ToRawFixed(x, intlObject.minimumFractionDigits, intlObject.maximumFractionDigits, intlObject.roundingIncrement, unsignedRoundingMode);
if (intlObject.roundingType === 'morePrecision') {
if (sResult.roundingMagnitude <= fResult.roundingMagnitude) {
result = sResult;
}
else {
result = fResult;
}
}
else {
invariant(intlObject.roundingType === 'lessPrecision', 'Invalid roundingType');
if (sResult.roundingMagnitude <= fResult.roundingMagnitude) {
result = fResult;
}
else {
result = sResult;
}
}
break;
}
x = result.roundedNumber;
var string = result.formattedString;
if (intlObject.trailingZeroDisplay === 'stripIfInteger' && x.isInteger()) {
var i = string.indexOf('.');
if (i > -1) {
string = string.slice(0, i);
}
}
var int = result.integerDigitsCount;
var minInteger = intlObject.minimumIntegerDigits;
if (int < minInteger) {
var forwardZeros = repeat('0', minInteger - int);
string = forwardZeros + string;
}
if (sign === 'negative') {
if (x.isZero()) {
x = NEGATIVE_ZERO;
}
else {
x = x.negated();
}
}
return { roundedNumber: x, formattedString: string };
let x = _x;
let sign;
// -0
if (x.isZero() && x.isNegative()) {
sign = "negative";
x = ZERO;
} else {
invariant(x.isFinite(), "NumberFormatDigitInternalSlots value is not finite");
if (x.lessThan(0)) {
sign = "negative";
} else {
sign = "positive";
}
if (sign === "negative") {
x = x.negated();
}
}
let result;
const roundingType = intlObject.roundingType;
const unsignedRoundingMode = GetUnsignedRoundingMode(intlObject.roundingMode, sign === "negative");
switch (roundingType) {
case "significantDigits":
result = ToRawPrecision(x, intlObject.minimumSignificantDigits, intlObject.maximumSignificantDigits, unsignedRoundingMode);
break;
case "fractionDigits":
result = ToRawFixed(x, intlObject.minimumFractionDigits, intlObject.maximumFractionDigits, intlObject.roundingIncrement, unsignedRoundingMode);
break;
default:
let sResult = ToRawPrecision(x, intlObject.minimumSignificantDigits, intlObject.maximumSignificantDigits, unsignedRoundingMode);
let fResult = ToRawFixed(x, intlObject.minimumFractionDigits, intlObject.maximumFractionDigits, intlObject.roundingIncrement, unsignedRoundingMode);
if (intlObject.roundingType === "morePrecision") {
if (sResult.roundingMagnitude <= fResult.roundingMagnitude) {
result = sResult;
} else {
result = fResult;
}
} else {
invariant(intlObject.roundingType === "lessPrecision", "Invalid roundingType");
if (sResult.roundingMagnitude <= fResult.roundingMagnitude) {
result = fResult;
} else {
result = sResult;
}
}
break;
}
x = result.roundedNumber;
let string = result.formattedString;
if (intlObject.trailingZeroDisplay === "stripIfInteger" && x.isInteger()) {
let i = string.indexOf(".");
if (i > -1) {
string = string.slice(0, i);
}
}
const int = result.integerDigitsCount;
const minInteger = intlObject.minimumIntegerDigits;
if (int < minInteger) {
const forwardZeros = repeat("0", minInteger - int);
string = forwardZeros + string;
}
if (sign === "negative") {
if (x.isZero()) {
x = NEGATIVE_ZERO;
} else {
x = x.negated();
}
}
return {
roundedNumber: x,
formattedString: string
};
}

@@ -1,2 +0,2 @@

import { RoundingModeType, UnsignedRoundingModeType } from '../types/number.js';
import { type RoundingModeType, type UnsignedRoundingModeType } from "../types/number.js";
export declare function GetUnsignedRoundingMode(roundingMode: RoundingModeType, isNegative: boolean): UnsignedRoundingModeType;

@@ -1,28 +0,29 @@

var negativeMapping = {
ceil: 'zero',
floor: 'infinity',
expand: 'infinity',
trunc: 'zero',
halfCeil: 'half-zero',
halfFloor: 'half-infinity',
halfExpand: 'half-infinity',
halfTrunc: 'half-zero',
halfEven: 'half-even',
import "../types/number.js";
const negativeMapping = {
ceil: "zero",
floor: "infinity",
expand: "infinity",
trunc: "zero",
halfCeil: "half-zero",
halfFloor: "half-infinity",
halfExpand: "half-infinity",
halfTrunc: "half-zero",
halfEven: "half-even"
};
var positiveMapping = {
ceil: 'infinity',
floor: 'zero',
expand: 'infinity',
trunc: 'zero',
halfCeil: 'half-infinity',
halfFloor: 'half-zero',
halfExpand: 'half-infinity',
halfTrunc: 'half-zero',
halfEven: 'half-even',
const positiveMapping = {
ceil: "infinity",
floor: "zero",
expand: "infinity",
trunc: "zero",
halfCeil: "half-infinity",
halfFloor: "half-zero",
halfExpand: "half-infinity",
halfTrunc: "half-zero",
halfEven: "half-even"
};
export function GetUnsignedRoundingMode(roundingMode, isNegative) {
if (isNegative) {
return negativeMapping[roundingMode];
}
return positiveMapping[roundingMode];
if (isNegative) {
return negativeMapping[roundingMode];
}
return positiveMapping[roundingMode];
}

@@ -1,12 +0,12 @@

import { NumberFormatInternal, NumberFormatLocaleInternalData, NumberFormatOptions } from '../types/number.js';
import { type NumberFormatInternal, type NumberFormatLocaleInternalData, type NumberFormatOptions } from "../types/number.js";
/**
* https://tc39.es/ecma402/#sec-initializenumberformat
*/
export declare function InitializeNumberFormat(nf: Intl.NumberFormat, locales: string | ReadonlyArray<string> | undefined, opts: NumberFormatOptions | undefined, { getInternalSlots, localeData, availableLocales, numberingSystemNames, getDefaultLocale, currencyDigitsData, }: {
getInternalSlots(nf: Intl.NumberFormat): NumberFormatInternal;
localeData: Record<string, NumberFormatLocaleInternalData | undefined>;
availableLocales: Set<string>;
numberingSystemNames: ReadonlyArray<string>;
getDefaultLocale(): string;
currencyDigitsData: Record<string, number>;
* https://tc39.es/ecma402/#sec-initializenumberformat
*/
export declare function InitializeNumberFormat(nf: Intl.NumberFormat, locales: string | ReadonlyArray<string> | undefined, opts: NumberFormatOptions | undefined, { getInternalSlots, localeData, availableLocales, numberingSystemNames, getDefaultLocale, currencyDigitsData }: {
getInternalSlots(nf: Intl.NumberFormat): NumberFormatInternal;
localeData: Record<string, NumberFormatLocaleInternalData | undefined>;
availableLocales: Set<string>;
numberingSystemNames: ReadonlyArray<string>;
getDefaultLocale(): string;
currencyDigitsData: Record<string, number>;
}): Intl.NumberFormat;

@@ -1,66 +0,85 @@

import { ResolveLocale } from '@formatjs/intl-localematcher';
import { CanonicalizeLocaleList } from '../CanonicalizeLocaleList.js';
import { CoerceOptionsToObject } from '../CoerceOptionsToObject.js';
import { GetOption } from '../GetOption.js';
import { GetStringOrBooleanOption } from '../GetStringOrBooleanOption.js';
import { invariant } from '../utils.js';
import { CurrencyDigits } from './CurrencyDigits.js';
import { SetNumberFormatDigitOptions } from './SetNumberFormatDigitOptions.js';
import { SetNumberFormatUnitOptions } from './SetNumberFormatUnitOptions.js';
import { ResolveLocale } from "@formatjs/intl-localematcher";
import { CanonicalizeLocaleList } from "../CanonicalizeLocaleList.js";
import { CoerceOptionsToObject } from "../CoerceOptionsToObject.js";
import { GetOption } from "../GetOption.js";
import { GetStringOrBooleanOption } from "../GetStringOrBooleanOption.js";
import "../types/number.js";
import { invariant } from "../utils.js";
import { CurrencyDigits } from "./CurrencyDigits.js";
import { SetNumberFormatDigitOptions } from "./SetNumberFormatDigitOptions.js";
import { SetNumberFormatUnitOptions } from "./SetNumberFormatUnitOptions.js";
/**
* https://tc39.es/ecma402/#sec-initializenumberformat
*/
export function InitializeNumberFormat(nf, locales, opts, _a) {
var getInternalSlots = _a.getInternalSlots, localeData = _a.localeData, availableLocales = _a.availableLocales, numberingSystemNames = _a.numberingSystemNames, getDefaultLocale = _a.getDefaultLocale, currencyDigitsData = _a.currencyDigitsData;
var requestedLocales = CanonicalizeLocaleList(locales);
var options = CoerceOptionsToObject(opts);
var opt = Object.create(null);
var matcher = GetOption(options, 'localeMatcher', 'string', ['lookup', 'best fit'], 'best fit');
opt.localeMatcher = matcher;
var numberingSystem = GetOption(options, 'numberingSystem', 'string', undefined, undefined);
if (numberingSystem !== undefined &&
numberingSystemNames.indexOf(numberingSystem) < 0) {
// 8.a. If numberingSystem does not match the Unicode Locale Identifier type nonterminal,
// throw a RangeError exception.
throw RangeError("Invalid numberingSystems: ".concat(numberingSystem));
}
opt.nu = numberingSystem;
var r = ResolveLocale(Array.from(availableLocales), requestedLocales, opt,
// [[RelevantExtensionKeys]] slot, which is a constant
['nu'], localeData, getDefaultLocale);
var dataLocaleData = localeData[r.dataLocale];
invariant(!!dataLocaleData, "Missing locale data for ".concat(r.dataLocale));
var internalSlots = getInternalSlots(nf);
internalSlots.locale = r.locale;
internalSlots.dataLocale = r.dataLocale;
internalSlots.numberingSystem = r.nu;
internalSlots.dataLocaleData = dataLocaleData;
SetNumberFormatUnitOptions(internalSlots, options);
var style = internalSlots.style;
var notation = GetOption(options, 'notation', 'string', ['standard', 'scientific', 'engineering', 'compact'], 'standard');
internalSlots.notation = notation;
var mnfdDefault;
var mxfdDefault;
if (style === 'currency' && notation === 'standard') {
var currency = internalSlots.currency;
var cDigits = CurrencyDigits(currency, { currencyDigitsData: currencyDigitsData });
mnfdDefault = cDigits;
mxfdDefault = cDigits;
}
else {
mnfdDefault = 0;
mxfdDefault = style === 'percent' ? 0 : 3;
}
SetNumberFormatDigitOptions(internalSlots, options, mnfdDefault, mxfdDefault, notation);
var compactDisplay = GetOption(options, 'compactDisplay', 'string', ['short', 'long'], 'short');
var defaultUseGrouping = 'auto';
if (notation === 'compact') {
internalSlots.compactDisplay = compactDisplay;
defaultUseGrouping = 'min2';
}
var useGrouping = GetStringOrBooleanOption(options, 'useGrouping', ['min2', 'auto', 'always'], 'always', false, defaultUseGrouping);
internalSlots.useGrouping = useGrouping;
var signDisplay = GetOption(options, 'signDisplay', 'string', ['auto', 'never', 'always', 'exceptZero', 'negative'], 'auto');
internalSlots.signDisplay = signDisplay;
return nf;
* https://tc39.es/ecma402/#sec-initializenumberformat
*/
export function InitializeNumberFormat(nf, locales, opts, { getInternalSlots, localeData, availableLocales, numberingSystemNames, getDefaultLocale, currencyDigitsData }) {
const requestedLocales = CanonicalizeLocaleList(locales);
const options = CoerceOptionsToObject(opts);
const opt = Object.create(null);
const matcher = GetOption(options, "localeMatcher", "string", ["lookup", "best fit"], "best fit");
opt.localeMatcher = matcher;
const numberingSystem = GetOption(options, "numberingSystem", "string", undefined, undefined);
if (numberingSystem !== undefined && numberingSystemNames.indexOf(numberingSystem) < 0) {
// 8.a. If numberingSystem does not match the Unicode Locale Identifier type nonterminal,
// throw a RangeError exception.
throw RangeError(`Invalid numberingSystems: ${numberingSystem}`);
}
opt.nu = numberingSystem;
const r = ResolveLocale(
Array.from(availableLocales),
requestedLocales,
opt,
// [[RelevantExtensionKeys]] slot, which is a constant
["nu"],
localeData,
getDefaultLocale
);
const dataLocaleData = localeData[r.dataLocale];
invariant(!!dataLocaleData, `Missing locale data for ${r.dataLocale}`);
const internalSlots = getInternalSlots(nf);
internalSlots.locale = r.locale;
internalSlots.dataLocale = r.dataLocale;
internalSlots.numberingSystem = r.nu;
internalSlots.dataLocaleData = dataLocaleData;
SetNumberFormatUnitOptions(internalSlots, options);
const style = internalSlots.style;
const notation = GetOption(options, "notation", "string", [
"standard",
"scientific",
"engineering",
"compact"
], "standard");
internalSlots.notation = notation;
let mnfdDefault;
let mxfdDefault;
if (style === "currency" && notation === "standard") {
const currency = internalSlots.currency;
const cDigits = CurrencyDigits(currency, { currencyDigitsData });
mnfdDefault = cDigits;
mxfdDefault = cDigits;
} else {
mnfdDefault = 0;
mxfdDefault = style === "percent" ? 0 : 3;
}
SetNumberFormatDigitOptions(internalSlots, options, mnfdDefault, mxfdDefault, notation);
const compactDisplay = GetOption(options, "compactDisplay", "string", ["short", "long"], "short");
let defaultUseGrouping = "auto";
if (notation === "compact") {
internalSlots.compactDisplay = compactDisplay;
defaultUseGrouping = "min2";
}
let useGrouping = GetStringOrBooleanOption(options, "useGrouping", [
"min2",
"auto",
"always"
], "always", false, defaultUseGrouping);
internalSlots.useGrouping = useGrouping;
let signDisplay = GetOption(options, "signDisplay", "string", [
"auto",
"never",
"always",
"exceptZero",
"negative"
], "auto");
internalSlots.signDisplay = signDisplay;
return nf;
}

@@ -1,6 +0,6 @@

import { Decimal } from 'decimal.js';
import { NumberFormatInternal, NumberFormatPart } from '../types/number.js';
import type { Decimal } from "decimal.js";
import { type NumberFormatInternal, type NumberFormatPart } from "../types/number.js";
/**
* https://tc39.es/ecma402/#sec-partitionnumberpattern
*/
* https://tc39.es/ecma402/#sec-partitionnumberpattern
*/
export declare function PartitionNumberPattern(internalSlots: NumberFormatInternal, _x: Decimal): NumberFormatPart[];

@@ -1,126 +0,115 @@

import { invariant } from '../utils.js';
import { ComputeExponent } from './ComputeExponent.js';
import formatToParts from './format_to_parts.js';
import { FormatNumericToString } from './FormatNumericToString.js';
import { getPowerOf10 } from './decimal-cache.js';
import "../types/number.js";
import { invariant } from "../utils.js";
import { ComputeExponent } from "./ComputeExponent.js";
import formatToParts from "./format_to_parts.js";
import { FormatNumericToString } from "./FormatNumericToString.js";
import { getPowerOf10 } from "./decimal-cache.js";
/**
* https://tc39.es/ecma402/#sec-partitionnumberpattern
*/
* https://tc39.es/ecma402/#sec-partitionnumberpattern
*/
export function PartitionNumberPattern(internalSlots, _x) {
var _a;
var x = _x;
// IMPL: We need to record the magnitude of the number
var magnitude = 0;
// 2. Let dataLocaleData be internalSlots.[[dataLocaleData]].
var pl = internalSlots.pl, dataLocaleData = internalSlots.dataLocaleData, numberingSystem = internalSlots.numberingSystem;
// 3. Let symbols be dataLocaleData.[[numbers]].[[symbols]][internalSlots.[[numberingSystem]]].
var symbols = dataLocaleData.numbers.symbols[numberingSystem] ||
dataLocaleData.numbers.symbols[dataLocaleData.numbers.nu[0]];
// 4. Let exponent be 0.
var exponent = 0;
// 5. Let n be ! ToString(x).
var n;
// 6. If x is NaN, then
if (x.isNaN()) {
// 6.a. Let n be symbols.[[nan]].
n = symbols.nan;
}
else if (!x.isFinite()) {
// 7. Else if x is a non-finite Number, then
// 7.a. Let n be symbols.[[infinity]].
n = symbols.infinity;
}
else {
// 8. Else,
if (!x.isZero()) {
// 8.a. If x < 0, let x be -x.
invariant(x.isFinite(), 'Input must be a mathematical value');
// 8.b. If internalSlots.[[style]] is "percent", let x be 100 × x.
if (internalSlots.style == 'percent') {
x = x.times(100);
}
// 8.c. Let exponent be ComputeExponent(numberFormat, x).
;
_a = ComputeExponent(internalSlots, x), exponent = _a[0],
// IMPL: We need to record the magnitude of the number
magnitude = _a[1];
// 8.d. Let x be x × 10^(-exponent).
x = x.times(getPowerOf10(-exponent));
}
// 8.e. Let formatNumberResult be FormatNumericToString(internalSlots, x).
var formatNumberResult = FormatNumericToString(internalSlots, x);
// 8.f. Let n be formatNumberResult.[[formattedString]].
n = formatNumberResult.formattedString;
// 8.g. Let x be formatNumberResult.[[roundedNumber]].
x = formatNumberResult.roundedNumber;
}
// 9. Let sign be 0.
var sign;
// 10. If x is negative, then
var signDisplay = internalSlots.signDisplay;
switch (signDisplay) {
case 'never':
// 10.a. If internalSlots.[[signDisplay]] is "never", then
// 10.a.i. Let sign be 0.
sign = 0;
break;
case 'auto':
// 10.b. Else if internalSlots.[[signDisplay]] is "auto", then
if (x.isPositive() || x.isNaN()) {
// 10.b.i. If x is positive or x is NaN, let sign be 0.
sign = 0;
}
else {
// 10.b.ii. Else, let sign be -1.
sign = -1;
}
break;
case 'always':
// 10.c. Else if internalSlots.[[signDisplay]] is "always", then
if (x.isPositive() || x.isNaN()) {
// 10.c.i. If x is positive or x is NaN, let sign be 1.
sign = 1;
}
else {
// 10.c.ii. Else, let sign be -1.
sign = -1;
}
break;
case 'exceptZero':
// 10.d. Else if internalSlots.[[signDisplay]] is "exceptZero", then
if (x.isZero()) {
// 10.d.i. If x is 0, let sign be 0.
sign = 0;
}
else if (x.isNegative()) {
// 10.d.ii. Else if x is negative, let sign be -1.
sign = -1;
}
else {
// 10.d.iii. Else, let sign be 1.
sign = 1;
}
break;
default:
// 10.e. Else,
invariant(signDisplay === 'negative', 'signDisplay must be "negative"');
if (x.isNegative() && !x.isZero()) {
// 10.e.i. If x is negative and x is not 0, let sign be -1.
sign = -1;
}
else {
// 10.e.ii. Else, let sign be 0.
sign = 0;
}
break;
}
// 11. Return ? FormatNumberToParts(numberFormat, x, n, exponent, sign).
return formatToParts({
roundedNumber: x,
formattedString: n,
exponent: exponent,
// IMPL: We're returning this for our implementation of formatToParts
magnitude: magnitude,
sign: sign,
}, internalSlots.dataLocaleData, pl, internalSlots);
let x = _x;
// IMPL: We need to record the magnitude of the number
let magnitude = 0;
// 2. Let dataLocaleData be internalSlots.[[dataLocaleData]].
const { pl, dataLocaleData, numberingSystem } = internalSlots;
// 3. Let symbols be dataLocaleData.[[numbers]].[[symbols]][internalSlots.[[numberingSystem]]].
const symbols = dataLocaleData.numbers.symbols[numberingSystem] || dataLocaleData.numbers.symbols[dataLocaleData.numbers.nu[0]];
// 4. Let exponent be 0.
let exponent = 0;
// 5. Let n be ! ToString(x).
let n;
// 6. If x is NaN, then
if (x.isNaN()) {
// 6.a. Let n be symbols.[[nan]].
n = symbols.nan;
} else if (!x.isFinite()) {
// 7. Else if x is a non-finite Number, then
// 7.a. Let n be symbols.[[infinity]].
n = symbols.infinity;
} else {
// 8. Else,
if (!x.isZero()) {
// 8.a. If x < 0, let x be -x.
invariant(x.isFinite(), "Input must be a mathematical value");
// 8.b. If internalSlots.[[style]] is "percent", let x be 100 × x.
if (internalSlots.style == "percent") {
x = x.times(100);
}
// 8.c. Let exponent be ComputeExponent(numberFormat, x).
;
[exponent, magnitude] = ComputeExponent(internalSlots, x);
// 8.d. Let x be x × 10^(-exponent).
x = x.times(getPowerOf10(-exponent));
}
// 8.e. Let formatNumberResult be FormatNumericToString(internalSlots, x).
const formatNumberResult = FormatNumericToString(internalSlots, x);
// 8.f. Let n be formatNumberResult.[[formattedString]].
n = formatNumberResult.formattedString;
// 8.g. Let x be formatNumberResult.[[roundedNumber]].
x = formatNumberResult.roundedNumber;
}
// 9. Let sign be 0.
let sign;
// 10. If x is negative, then
const signDisplay = internalSlots.signDisplay;
switch (signDisplay) {
case "never":
// 10.a. If internalSlots.[[signDisplay]] is "never", then
// 10.a.i. Let sign be 0.
sign = 0;
break;
case "auto":
// 10.b. Else if internalSlots.[[signDisplay]] is "auto", then
if (x.isPositive() || x.isNaN()) {
// 10.b.i. If x is positive or x is NaN, let sign be 0.
sign = 0;
} else {
// 10.b.ii. Else, let sign be -1.
sign = -1;
}
break;
case "always":
// 10.c. Else if internalSlots.[[signDisplay]] is "always", then
if (x.isPositive() || x.isNaN()) {
// 10.c.i. If x is positive or x is NaN, let sign be 1.
sign = 1;
} else {
// 10.c.ii. Else, let sign be -1.
sign = -1;
}
break;
case "exceptZero":
// 10.d. Else if internalSlots.[[signDisplay]] is "exceptZero", then
if (x.isZero()) {
// 10.d.i. If x is 0, let sign be 0.
sign = 0;
} else if (x.isNegative()) {
// 10.d.ii. Else if x is negative, let sign be -1.
sign = -1;
} else {
// 10.d.iii. Else, let sign be 1.
sign = 1;
}
break;
default:
// 10.e. Else,
invariant(signDisplay === "negative", "signDisplay must be \"negative\"");
if (x.isNegative() && !x.isZero()) {
// 10.e.i. If x is negative and x is not 0, let sign be -1.
sign = -1;
} else {
// 10.e.ii. Else, let sign be 0.
sign = 0;
}
break;
}
// 11. Return ? FormatNumberToParts(numberFormat, x, n, exponent, sign).
return formatToParts({
roundedNumber: x,
formattedString: n,
exponent,
magnitude,
sign
}, internalSlots.dataLocaleData, pl, internalSlots);
}

@@ -1,8 +0,8 @@

import { Decimal } from 'decimal.js';
import { NumberFormatInternal, NumberFormatPart } from '../types/number.js';
import type { Decimal } from "decimal.js";
import { type NumberFormatInternal, type NumberFormatPart } from "../types/number.js";
/**
* https://tc39.es/ecma402/#sec-partitionnumberrangepattern
*/
export declare function PartitionNumberRangePattern(numberFormat: Intl.NumberFormat, x: Decimal, y: Decimal, { getInternalSlots, }: {
getInternalSlots(nf: Intl.NumberFormat): NumberFormatInternal;
* https://tc39.es/ecma402/#sec-partitionnumberrangepattern
*/
export declare function PartitionNumberRangePattern(numberFormat: Intl.NumberFormat, x: Decimal, y: Decimal, { getInternalSlots }: {
getInternalSlots(nf: Intl.NumberFormat): NumberFormatInternal;
}): NumberFormatPart[];

@@ -1,40 +0,43 @@

import { invariant } from '../utils.js';
import { CollapseNumberRange } from './CollapseNumberRange.js';
import { FormatApproximately } from './FormatApproximately.js';
import { FormatNumeric } from './FormatNumeric.js';
import { PartitionNumberPattern } from './PartitionNumberPattern.js';
import "../types/number.js";
import { invariant } from "../utils.js";
import { CollapseNumberRange } from "./CollapseNumberRange.js";
import { FormatApproximately } from "./FormatApproximately.js";
import { FormatNumeric } from "./FormatNumeric.js";
import { PartitionNumberPattern } from "./PartitionNumberPattern.js";
/**
* https://tc39.es/ecma402/#sec-partitionnumberrangepattern
*/
export function PartitionNumberRangePattern(numberFormat, x, y, _a) {
var getInternalSlots = _a.getInternalSlots;
// 1. Assert: x and y are both mathematical values.
invariant(!x.isNaN() && !y.isNaN(), 'Input must be a number', RangeError);
var internalSlots = getInternalSlots(numberFormat);
// 3. Let xResult be ? PartitionNumberPattern(numberFormat, x).
var xResult = PartitionNumberPattern(internalSlots, x);
// 4. Let yResult be ? PartitionNumberPattern(numberFormat, y).
var yResult = PartitionNumberPattern(internalSlots, y);
if (FormatNumeric(internalSlots, x) === FormatNumeric(internalSlots, y)) {
var appxResult = FormatApproximately(internalSlots, xResult);
appxResult.forEach(function (el) {
el.source = 'shared';
});
return appxResult;
}
var result = [];
xResult.forEach(function (el) {
el.source = 'startRange';
result.push(el);
});
// 9. Let symbols be internalSlots.[[dataLocaleData]].[[numbers]].[[symbols]][internalSlots.[[numberingSystem]]].
var rangeSeparator = internalSlots.dataLocaleData.numbers.symbols[internalSlots.numberingSystem]
.rangeSign;
result.push({ type: 'literal', value: rangeSeparator, source: 'shared' });
yResult.forEach(function (el) {
el.source = 'endRange';
result.push(el);
});
// 13. Return ? CollapseNumberRange(numberFormat, result).
return CollapseNumberRange(numberFormat, result, { getInternalSlots: getInternalSlots });
* https://tc39.es/ecma402/#sec-partitionnumberrangepattern
*/
export function PartitionNumberRangePattern(numberFormat, x, y, { getInternalSlots }) {
// 1. Assert: x and y are both mathematical values.
invariant(!x.isNaN() && !y.isNaN(), "Input must be a number", RangeError);
const internalSlots = getInternalSlots(numberFormat);
// 3. Let xResult be ? PartitionNumberPattern(numberFormat, x).
const xResult = PartitionNumberPattern(internalSlots, x);
// 4. Let yResult be ? PartitionNumberPattern(numberFormat, y).
const yResult = PartitionNumberPattern(internalSlots, y);
if (FormatNumeric(internalSlots, x) === FormatNumeric(internalSlots, y)) {
const appxResult = FormatApproximately(internalSlots, xResult);
appxResult.forEach((el) => {
el.source = "shared";
});
return appxResult;
}
let result = [];
xResult.forEach((el) => {
el.source = "startRange";
result.push(el);
});
// 9. Let symbols be internalSlots.[[dataLocaleData]].[[numbers]].[[symbols]][internalSlots.[[numberingSystem]]].
const rangeSeparator = internalSlots.dataLocaleData.numbers.symbols[internalSlots.numberingSystem].rangeSign;
result.push({
type: "literal",
value: rangeSeparator,
source: "shared"
});
yResult.forEach((el) => {
el.source = "endRange";
result.push(el);
});
// 13. Return ? CollapseNumberRange(numberFormat, result).
return CollapseNumberRange(numberFormat, result, { getInternalSlots });
}

@@ -1,5 +0,5 @@

import { NumberFormatDigitInternalSlots, NumberFormatDigitOptions, NumberFormatNotation } from '../types/number.js';
import { type NumberFormatDigitInternalSlots, type NumberFormatDigitOptions, type NumberFormatNotation } from "../types/number.js";
/**
* https://tc39.es/ecma402/#sec-setnfdigitoptions
*/
* https://tc39.es/ecma402/#sec-setnfdigitoptions
*/
export declare function SetNumberFormatDigitOptions(internalSlots: NumberFormatDigitInternalSlots, opts: NumberFormatDigitOptions, mnfdDefault: number, mxfdDefault: number, notation: NumberFormatNotation): void;

@@ -1,179 +0,190 @@

import { DefaultNumberOption } from '../DefaultNumberOption.js';
import { GetNumberOption } from '../GetNumberOption.js';
import { GetOption } from '../GetOption.js';
import { invariant } from '../utils.js';
import { DefaultNumberOption } from "../DefaultNumberOption.js";
import { GetNumberOption } from "../GetNumberOption.js";
import { GetOption } from "../GetOption.js";
import "../types/number.js";
import { invariant } from "../utils.js";
//IMPL: Valid rounding increments as per implementation
var VALID_ROUNDING_INCREMENTS = new Set([
1, 2, 5, 10, 20, 25, 50, 100, 200, 250, 500, 1000, 2000, 2500, 5000,
const VALID_ROUNDING_INCREMENTS = new Set([
1,
2,
5,
10,
20,
25,
50,
100,
200,
250,
500,
1e3,
2e3,
2500,
5e3
]);
/**
* https://tc39.es/ecma402/#sec-setnfdigitoptions
*/
* https://tc39.es/ecma402/#sec-setnfdigitoptions
*/
export function SetNumberFormatDigitOptions(internalSlots, opts, mnfdDefault, mxfdDefault, notation) {
// 1. Let mnid be ? GetNumberOption(opts, "minimumIntegerDigits", 1, 21, 1).
var mnid = GetNumberOption(opts, 'minimumIntegerDigits', 1, 21, 1);
// 2. Let mnfd be opts.[[MinimumFractionDigits]].
var mnfd = opts.minimumFractionDigits;
// 3. Let mxfd be opts.[[MaximumFractionDigits]].
var mxfd = opts.maximumFractionDigits;
// 4. Let mnsd be opts.[[MinimumSignificantDigits]].
var mnsd = opts.minimumSignificantDigits;
// 5. Let mxsd be opts.[[MaximumSignificantDigits]].
var mxsd = opts.maximumSignificantDigits;
// 6. Set internalSlots.[[MinimumIntegerDigits]] to mnid.
internalSlots.minimumIntegerDigits = mnid;
// 7. Let roundingIncrement be ? GetNumberOption(opts, "roundingIncrement", 1, 5000, 1).
var roundingIncrement = GetNumberOption(opts, 'roundingIncrement', 1, 5000, 1);
// 8. If roundingIncrement is not an element of the list {1, 2, 5, 10, 20, 25, 50, 100, 200, 250, 500, 1000, 2000, 2500, 5000}, throw a RangeError exception.
invariant(VALID_ROUNDING_INCREMENTS.has(roundingIncrement), "Invalid rounding increment value: ".concat(roundingIncrement, ".\nValid values are ").concat(Array.from(VALID_ROUNDING_INCREMENTS).join(', '), "."));
// 9. Let roundingMode be ? GetOption(opts, "roundingMode", "string", « "ceil", "floor", "expand", "trunc", "halfCeil", "halfFloor", "halfExpand", "halfTrunc", "halfEven" », "halfExpand").
var roundingMode = GetOption(opts, 'roundingMode', 'string', [
'ceil',
'floor',
'expand',
'trunc',
'halfCeil',
'halfFloor',
'halfExpand',
'halfTrunc',
'halfEven',
], 'halfExpand');
// 10. Let roundingPriority be ? GetOption(opts, "roundingPriority", "string", « "auto", "morePrecision", "lessPrecision" », "auto").
var roundingPriority = GetOption(opts, 'roundingPriority', 'string', ['auto', 'morePrecision', 'lessPrecision'], 'auto');
// 11. Let trailingZeroDisplay be ? GetOption(opts, "trailingZeroDisplay", "string", « "auto", "stripIfInteger" », "auto").
var trailingZeroDisplay = GetOption(opts, 'trailingZeroDisplay', 'string', ['auto', 'stripIfInteger'], 'auto');
// 12. If roundingIncrement is not 1, then
if (roundingIncrement !== 1) {
// 12.a. Set mxfdDefault to mnfdDefault.
mxfdDefault = mnfdDefault;
}
// 13. Set internalSlots.[[RoundingIncrement]] to roundingIncrement.
internalSlots.roundingIncrement = roundingIncrement;
// 14. Set internalSlots.[[RoundingMode]] to roundingMode.
internalSlots.roundingMode = roundingMode;
// 15. Set internalSlots.[[TrailingZeroDisplay]] to trailingZeroDisplay.
internalSlots.trailingZeroDisplay = trailingZeroDisplay;
// 16. Let hasSd be true if mnsd is not undefined or mxsd is not undefined; otherwise, let hasSd be false.
var hasSd = mnsd !== undefined || mxsd !== undefined;
// 17. Let hasFd be true if mnfd is not undefined or mxfd is not undefined; otherwise, let hasFd be false.
var hasFd = mnfd !== undefined || mxfd !== undefined;
// 18. Let needSd be true.
var needSd = true;
// 19. Let needFd be true.
var needFd = true;
// 20. If roundingPriority is "auto", then
if (roundingPriority === 'auto') {
// 20.a. Set needSd to hasSd.
needSd = hasSd;
// 20.b. If hasSd is true or hasFd is false and notation is "compact", then
if (hasSd || (!hasFd && notation === 'compact')) {
// 20.b.i. Set needFd to false.
needFd = false;
}
}
// 21. If needSd is true, then
if (needSd) {
// 21.a. If hasSd is true, then
if (hasSd) {
// 21.a.i. Set internalSlots.[[MinimumSignificantDigits]] to ? DefaultNumberOption(mnsd, 1, 21, 1).
internalSlots.minimumSignificantDigits = DefaultNumberOption(mnsd, 1, 21, 1);
// 21.a.ii. Set internalSlots.[[MaximumSignificantDigits]] to ? DefaultNumberOption(mxsd, internalSlots.[[MinimumSignificantDigits]], 21, 21).
internalSlots.maximumSignificantDigits = DefaultNumberOption(mxsd, internalSlots.minimumSignificantDigits, 21, 21);
}
else {
// 21.b. Else,
// 21.b.i. Set internalSlots.[[MinimumSignificantDigits]] to 1.
internalSlots.minimumSignificantDigits = 1;
// 21.b.ii. Set internalSlots.[[MaximumSignificantDigits]] to 21.
internalSlots.maximumSignificantDigits = 21;
}
}
// 22. If needFd is true, then
if (needFd) {
// 22.a. If hasFd is true, then
if (hasFd) {
// 22.a.i. Set mnfd to ? DefaultNumberOption(mnfd, 0, 100, undefined).
mnfd = DefaultNumberOption(mnfd, 0, 100, undefined);
// 22.a.ii. Set mxfd to ? DefaultNumberOption(mxfd, 0, 100, undefined).
mxfd = DefaultNumberOption(mxfd, 0, 100, undefined);
// 22.a.iii. If mnfd is undefined, then
if (mnfd === undefined) {
// 22.a.iii.1. Assert: mxfd is not undefined.
invariant(mxfd !== undefined, 'maximumFractionDigits must be defined');
// 22.a.iii.2. Set mnfd to min(mnfdDefault, mxfd).
mnfd = Math.min(mnfdDefault, mxfd);
}
else if (mxfd === undefined) {
// 22.a.iv. Else if mxfd is undefined, then
// 22.a.iv.1. Set mxfd to max(mxfdDefault, mnfd).
mxfd = Math.max(mxfdDefault, mnfd);
}
else if (mnfd > mxfd) {
// 22.a.v. Else if mnfd > mxfd, throw a RangeError exception.
throw new RangeError("Invalid range, ".concat(mnfd, " > ").concat(mxfd));
}
// 22.a.vi. Set internalSlots.[[MinimumFractionDigits]] to mnfd.
internalSlots.minimumFractionDigits = mnfd;
// 22.a.vii. Set internalSlots.[[MaximumFractionDigits]] to mxfd.
internalSlots.maximumFractionDigits = mxfd;
}
else {
// 22.b. Else,
// 22.b.i. Set internalSlots.[[MinimumFractionDigits]] to mnfdDefault.
internalSlots.minimumFractionDigits = mnfdDefault;
// 22.b.ii. Set internalSlots.[[MaximumFractionDigits]] to mxfdDefault.
internalSlots.maximumFractionDigits = mxfdDefault;
}
}
// 23. If needSd is false and needFd is false, then
if (!needSd && !needFd) {
// 23.a. Set internalSlots.[[MinimumFractionDigits]] to 0.
internalSlots.minimumFractionDigits = 0;
// 23.b. Set internalSlots.[[MaximumFractionDigits]] to 0.
internalSlots.maximumFractionDigits = 0;
// 23.c. Set internalSlots.[[MinimumSignificantDigits]] to 1.
internalSlots.minimumSignificantDigits = 1;
// 23.d. Set internalSlots.[[MaximumSignificantDigits]] to 2.
internalSlots.maximumSignificantDigits = 2;
// 23.e. Set internalSlots.[[RoundingType]] to "morePrecision".
internalSlots.roundingType = 'morePrecision';
// 23.f. Set internalSlots.[[RoundingPriority]] to "morePrecision".
internalSlots.roundingPriority = 'morePrecision';
}
else if (roundingPriority === 'morePrecision') {
// 24. Else if roundingPriority is "morePrecision", then
// 24.a. Set internalSlots.[[RoundingType]] to "morePrecision".
internalSlots.roundingType = 'morePrecision';
// 24.b. Set internalSlots.[[RoundingPriority]] to "morePrecision".
internalSlots.roundingPriority = 'morePrecision';
}
else if (roundingPriority === 'lessPrecision') {
// 25. Else if roundingPriority is "lessPrecision", then
// 25.a. Set internalSlots.[[RoundingType]] to "lessPrecision".
internalSlots.roundingType = 'lessPrecision';
// 25.b. Set internalSlots.[[RoundingPriority]] to "lessPrecision".
internalSlots.roundingPriority = 'lessPrecision';
}
else if (hasSd) {
// 26. Else if hasSd is true, then
// 26.a. Set internalSlots.[[RoundingType]] to "significantDigits".
internalSlots.roundingType = 'significantDigits';
// 26.b. Set internalSlots.[[RoundingPriority]] to "auto".
internalSlots.roundingPriority = 'auto';
}
else {
// 27. Else,
// 27.a. Set internalSlots.[[RoundingType]] to "fractionDigits".
internalSlots.roundingType = 'fractionDigits';
// 27.b. Set internalSlots.[[RoundingPriority]] to "auto".
internalSlots.roundingPriority = 'auto';
}
// 28. If roundingIncrement is not 1, then
if (roundingIncrement !== 1) {
// 28.a. Assert: internalSlots.[[RoundingType]] is "fractionDigits".
invariant(internalSlots.roundingType === 'fractionDigits', 'Invalid roundingType', TypeError);
// 28.b. Assert: internalSlots.[[MaximumFractionDigits]] is equal to internalSlots.[[MinimumFractionDigits]].
invariant(internalSlots.maximumFractionDigits ===
internalSlots.minimumFractionDigits, 'With roundingIncrement > 1, maximumFractionDigits and minimumFractionDigits must be equal.', RangeError);
}
// 1. Let mnid be ? GetNumberOption(opts, "minimumIntegerDigits", 1, 21, 1).
const mnid = GetNumberOption(opts, "minimumIntegerDigits", 1, 21, 1);
// 2. Let mnfd be opts.[[MinimumFractionDigits]].
let mnfd = opts.minimumFractionDigits;
// 3. Let mxfd be opts.[[MaximumFractionDigits]].
let mxfd = opts.maximumFractionDigits;
// 4. Let mnsd be opts.[[MinimumSignificantDigits]].
let mnsd = opts.minimumSignificantDigits;
// 5. Let mxsd be opts.[[MaximumSignificantDigits]].
let mxsd = opts.maximumSignificantDigits;
// 6. Set internalSlots.[[MinimumIntegerDigits]] to mnid.
internalSlots.minimumIntegerDigits = mnid;
// 7. Let roundingIncrement be ? GetNumberOption(opts, "roundingIncrement", 1, 5000, 1).
const roundingIncrement = GetNumberOption(opts, "roundingIncrement", 1, 5e3, 1);
// 8. If roundingIncrement is not an element of the list {1, 2, 5, 10, 20, 25, 50, 100, 200, 250, 500, 1000, 2000, 2500, 5000}, throw a RangeError exception.
invariant(VALID_ROUNDING_INCREMENTS.has(roundingIncrement), `Invalid rounding increment value: ${roundingIncrement}.
Valid values are ${Array.from(VALID_ROUNDING_INCREMENTS).join(", ")}.`);
// 9. Let roundingMode be ? GetOption(opts, "roundingMode", "string", « "ceil", "floor", "expand", "trunc", "halfCeil", "halfFloor", "halfExpand", "halfTrunc", "halfEven" », "halfExpand").
const roundingMode = GetOption(opts, "roundingMode", "string", [
"ceil",
"floor",
"expand",
"trunc",
"halfCeil",
"halfFloor",
"halfExpand",
"halfTrunc",
"halfEven"
], "halfExpand");
// 10. Let roundingPriority be ? GetOption(opts, "roundingPriority", "string", « "auto", "morePrecision", "lessPrecision" », "auto").
const roundingPriority = GetOption(opts, "roundingPriority", "string", [
"auto",
"morePrecision",
"lessPrecision"
], "auto");
// 11. Let trailingZeroDisplay be ? GetOption(opts, "trailingZeroDisplay", "string", « "auto", "stripIfInteger" », "auto").
const trailingZeroDisplay = GetOption(opts, "trailingZeroDisplay", "string", ["auto", "stripIfInteger"], "auto");
// 12. If roundingIncrement is not 1, then
if (roundingIncrement !== 1) {
// 12.a. Set mxfdDefault to mnfdDefault.
mxfdDefault = mnfdDefault;
}
// 13. Set internalSlots.[[RoundingIncrement]] to roundingIncrement.
internalSlots.roundingIncrement = roundingIncrement;
// 14. Set internalSlots.[[RoundingMode]] to roundingMode.
internalSlots.roundingMode = roundingMode;
// 15. Set internalSlots.[[TrailingZeroDisplay]] to trailingZeroDisplay.
internalSlots.trailingZeroDisplay = trailingZeroDisplay;
// 16. Let hasSd be true if mnsd is not undefined or mxsd is not undefined; otherwise, let hasSd be false.
const hasSd = mnsd !== undefined || mxsd !== undefined;
// 17. Let hasFd be true if mnfd is not undefined or mxfd is not undefined; otherwise, let hasFd be false.
const hasFd = mnfd !== undefined || mxfd !== undefined;
// 18. Let needSd be true.
let needSd = true;
// 19. Let needFd be true.
let needFd = true;
// 20. If roundingPriority is "auto", then
if (roundingPriority === "auto") {
// 20.a. Set needSd to hasSd.
needSd = hasSd;
// 20.b. If hasSd is true or hasFd is false and notation is "compact", then
if (hasSd || !hasFd && notation === "compact") {
// 20.b.i. Set needFd to false.
needFd = false;
}
}
// 21. If needSd is true, then
if (needSd) {
// 21.a. If hasSd is true, then
if (hasSd) {
// 21.a.i. Set internalSlots.[[MinimumSignificantDigits]] to ? DefaultNumberOption(mnsd, 1, 21, 1).
internalSlots.minimumSignificantDigits = DefaultNumberOption(mnsd, 1, 21, 1);
// 21.a.ii. Set internalSlots.[[MaximumSignificantDigits]] to ? DefaultNumberOption(mxsd, internalSlots.[[MinimumSignificantDigits]], 21, 21).
internalSlots.maximumSignificantDigits = DefaultNumberOption(mxsd, internalSlots.minimumSignificantDigits, 21, 21);
} else {
// 21.b. Else,
// 21.b.i. Set internalSlots.[[MinimumSignificantDigits]] to 1.
internalSlots.minimumSignificantDigits = 1;
// 21.b.ii. Set internalSlots.[[MaximumSignificantDigits]] to 21.
internalSlots.maximumSignificantDigits = 21;
}
}
// 22. If needFd is true, then
if (needFd) {
// 22.a. If hasFd is true, then
if (hasFd) {
// 22.a.i. Set mnfd to ? DefaultNumberOption(mnfd, 0, 100, undefined).
mnfd = DefaultNumberOption(mnfd, 0, 100, undefined);
// 22.a.ii. Set mxfd to ? DefaultNumberOption(mxfd, 0, 100, undefined).
mxfd = DefaultNumberOption(mxfd, 0, 100, undefined);
// 22.a.iii. If mnfd is undefined, then
if (mnfd === undefined) {
// 22.a.iii.1. Assert: mxfd is not undefined.
invariant(mxfd !== undefined, "maximumFractionDigits must be defined");
// 22.a.iii.2. Set mnfd to min(mnfdDefault, mxfd).
mnfd = Math.min(mnfdDefault, mxfd);
} else if (mxfd === undefined) {
// 22.a.iv. Else if mxfd is undefined, then
// 22.a.iv.1. Set mxfd to max(mxfdDefault, mnfd).
mxfd = Math.max(mxfdDefault, mnfd);
} else if (mnfd > mxfd) {
// 22.a.v. Else if mnfd > mxfd, throw a RangeError exception.
throw new RangeError(`Invalid range, ${mnfd} > ${mxfd}`);
}
// 22.a.vi. Set internalSlots.[[MinimumFractionDigits]] to mnfd.
internalSlots.minimumFractionDigits = mnfd;
// 22.a.vii. Set internalSlots.[[MaximumFractionDigits]] to mxfd.
internalSlots.maximumFractionDigits = mxfd;
} else {
// 22.b. Else,
// 22.b.i. Set internalSlots.[[MinimumFractionDigits]] to mnfdDefault.
internalSlots.minimumFractionDigits = mnfdDefault;
// 22.b.ii. Set internalSlots.[[MaximumFractionDigits]] to mxfdDefault.
internalSlots.maximumFractionDigits = mxfdDefault;
}
}
// 23. If needSd is false and needFd is false, then
if (!needSd && !needFd) {
// 23.a. Set internalSlots.[[MinimumFractionDigits]] to 0.
internalSlots.minimumFractionDigits = 0;
// 23.b. Set internalSlots.[[MaximumFractionDigits]] to 0.
internalSlots.maximumFractionDigits = 0;
// 23.c. Set internalSlots.[[MinimumSignificantDigits]] to 1.
internalSlots.minimumSignificantDigits = 1;
// 23.d. Set internalSlots.[[MaximumSignificantDigits]] to 2.
internalSlots.maximumSignificantDigits = 2;
// 23.e. Set internalSlots.[[RoundingType]] to "morePrecision".
internalSlots.roundingType = "morePrecision";
// 23.f. Set internalSlots.[[RoundingPriority]] to "morePrecision".
internalSlots.roundingPriority = "morePrecision";
} else if (roundingPriority === "morePrecision") {
// 24. Else if roundingPriority is "morePrecision", then
// 24.a. Set internalSlots.[[RoundingType]] to "morePrecision".
internalSlots.roundingType = "morePrecision";
// 24.b. Set internalSlots.[[RoundingPriority]] to "morePrecision".
internalSlots.roundingPriority = "morePrecision";
} else if (roundingPriority === "lessPrecision") {
// 25. Else if roundingPriority is "lessPrecision", then
// 25.a. Set internalSlots.[[RoundingType]] to "lessPrecision".
internalSlots.roundingType = "lessPrecision";
// 25.b. Set internalSlots.[[RoundingPriority]] to "lessPrecision".
internalSlots.roundingPriority = "lessPrecision";
} else if (hasSd) {
// 26. Else if hasSd is true, then
// 26.a. Set internalSlots.[[RoundingType]] to "significantDigits".
internalSlots.roundingType = "significantDigits";
// 26.b. Set internalSlots.[[RoundingPriority]] to "auto".
internalSlots.roundingPriority = "auto";
} else {
// 27. Else,
// 27.a. Set internalSlots.[[RoundingType]] to "fractionDigits".
internalSlots.roundingType = "fractionDigits";
// 27.b. Set internalSlots.[[RoundingPriority]] to "auto".
internalSlots.roundingPriority = "auto";
}
// 28. If roundingIncrement is not 1, then
if (roundingIncrement !== 1) {
// 28.a. Assert: internalSlots.[[RoundingType]] is "fractionDigits".
invariant(internalSlots.roundingType === "fractionDigits", "Invalid roundingType", TypeError);
// 28.b. Assert: internalSlots.[[MaximumFractionDigits]] is equal to internalSlots.[[MinimumFractionDigits]].
invariant(internalSlots.maximumFractionDigits === internalSlots.minimumFractionDigits, "With roundingIncrement > 1, maximumFractionDigits and minimumFractionDigits must be equal.", RangeError);
}
}

@@ -1,5 +0,5 @@

import { NumberFormatInternal, NumberFormatOptions } from '../types/number.js';
import { type NumberFormatInternal, type NumberFormatOptions } from "../types/number.js";
/**
* https://tc39.es/ecma402/#sec-setnumberformatunitoptions
*/
* https://tc39.es/ecma402/#sec-setnumberformatunitoptions
*/
export declare function SetNumberFormatUnitOptions(internalSlots: NumberFormatInternal, options?: NumberFormatOptions | undefined): void;

@@ -1,50 +0,64 @@

import { GetOption } from '../GetOption.js';
import { IsWellFormedCurrencyCode } from '../IsWellFormedCurrencyCode.js';
import { IsWellFormedUnitIdentifier } from '../IsWellFormedUnitIdentifier.js';
import { invariant } from '../utils.js';
import { GetOption } from "../GetOption.js";
import { IsWellFormedCurrencyCode } from "../IsWellFormedCurrencyCode.js";
import { IsWellFormedUnitIdentifier } from "../IsWellFormedUnitIdentifier.js";
import "../types/number.js";
import { invariant } from "../utils.js";
/**
* https://tc39.es/ecma402/#sec-setnumberformatunitoptions
*/
export function SetNumberFormatUnitOptions(internalSlots, options) {
if (options === void 0) { options = Object.create(null); }
// 1. Let style be ? GetOption(options, "style", "string", « "decimal", "percent", "currency", "unit" », "decimal").
var style = GetOption(options, 'style', 'string', ['decimal', 'percent', 'currency', 'unit'], 'decimal');
// 2. Set internalSlots.[[Style]] to style.
internalSlots.style = style;
// 3. Let currency be ? GetOption(options, "currency", "string", undefined, undefined).
var currency = GetOption(options, 'currency', 'string', undefined, undefined);
// 4. If currency is not undefined, then
// a. If the result of IsWellFormedCurrencyCode(currency) is false, throw a RangeError exception.
invariant(currency === undefined || IsWellFormedCurrencyCode(currency), 'Malformed currency code', RangeError);
// 5. If style is "currency" and currency is undefined, throw a TypeError exception.
invariant(style !== 'currency' || currency !== undefined, 'currency cannot be undefined', TypeError);
// 6. Let currencyDisplay be ? GetOption(options, "currencyDisplay", "string", « "code", "symbol", "narrowSymbol", "name" », "symbol").
var currencyDisplay = GetOption(options, 'currencyDisplay', 'string', ['code', 'symbol', 'narrowSymbol', 'name'], 'symbol');
// 7. Let currencySign be ? GetOption(options, "currencySign", "string", « "standard", "accounting" », "standard").
var currencySign = GetOption(options, 'currencySign', 'string', ['standard', 'accounting'], 'standard');
// 8. Let unit be ? GetOption(options, "unit", "string", undefined, undefined).
var unit = GetOption(options, 'unit', 'string', undefined, undefined);
// 9. If unit is not undefined, then
// a. If the result of IsWellFormedUnitIdentifier(unit) is false, throw a RangeError exception.
invariant(unit === undefined || IsWellFormedUnitIdentifier(unit), 'Invalid unit argument for Intl.NumberFormat()', RangeError);
// 10. If style is "unit" and unit is undefined, throw a TypeError exception.
invariant(style !== 'unit' || unit !== undefined, 'unit cannot be undefined', TypeError);
// 11. Let unitDisplay be ? GetOption(options, "unitDisplay", "string", « "short", "narrow", "long" », "short").
var unitDisplay = GetOption(options, 'unitDisplay', 'string', ['short', 'narrow', 'long'], 'short');
// 12. If style is "currency", then
if (style === 'currency') {
// a. Set internalSlots.[[Currency]] to the result of converting currency to upper case as specified in 6.1.
internalSlots.currency = currency.toUpperCase();
// b. Set internalSlots.[[CurrencyDisplay]] to currencyDisplay.
internalSlots.currencyDisplay = currencyDisplay;
// c. Set internalSlots.[[CurrencySign]] to currencySign.
internalSlots.currencySign = currencySign;
}
// 13. If style is "unit", then
if (style === 'unit') {
// a. Set internalSlots.[[Unit]] to unit.
internalSlots.unit = unit;
// b. Set internalSlots.[[UnitDisplay]] to unitDisplay.
internalSlots.unitDisplay = unitDisplay;
}
* https://tc39.es/ecma402/#sec-setnumberformatunitoptions
*/
export function SetNumberFormatUnitOptions(internalSlots, options = Object.create(null)) {
// 1. Let style be ? GetOption(options, "style", "string", « "decimal", "percent", "currency", "unit" », "decimal").
const style = GetOption(options, "style", "string", [
"decimal",
"percent",
"currency",
"unit"
], "decimal");
// 2. Set internalSlots.[[Style]] to style.
internalSlots.style = style;
// 3. Let currency be ? GetOption(options, "currency", "string", undefined, undefined).
const currency = GetOption(options, "currency", "string", undefined, undefined);
// 4. If currency is not undefined, then
// a. If the result of IsWellFormedCurrencyCode(currency) is false, throw a RangeError exception.
invariant(currency === undefined || IsWellFormedCurrencyCode(currency), "Malformed currency code", RangeError);
// 5. If style is "currency" and currency is undefined, throw a TypeError exception.
invariant(style !== "currency" || currency !== undefined, "currency cannot be undefined", TypeError);
// 6. Let currencyDisplay be ? GetOption(options, "currencyDisplay", "string", « "code", "symbol", "narrowSymbol", "name" », "symbol").
const currencyDisplay = GetOption(options, "currencyDisplay", "string", [
"code",
"symbol",
"narrowSymbol",
"name"
], "symbol");
// 7. Let currencySign be ? GetOption(options, "currencySign", "string", « "standard", "accounting" », "standard").
const currencySign = GetOption(options, "currencySign", "string", ["standard", "accounting"], "standard");
// 8. Let unit be ? GetOption(options, "unit", "string", undefined, undefined).
const unit = GetOption(options, "unit", "string", undefined, undefined);
// 9. If unit is not undefined, then
// a. If the result of IsWellFormedUnitIdentifier(unit) is false, throw a RangeError exception.
invariant(unit === undefined || IsWellFormedUnitIdentifier(unit), "Invalid unit argument for Intl.NumberFormat()", RangeError);
// 10. If style is "unit" and unit is undefined, throw a TypeError exception.
invariant(style !== "unit" || unit !== undefined, "unit cannot be undefined", TypeError);
// 11. Let unitDisplay be ? GetOption(options, "unitDisplay", "string", « "short", "narrow", "long" », "short").
const unitDisplay = GetOption(options, "unitDisplay", "string", [
"short",
"narrow",
"long"
], "short");
// 12. If style is "currency", then
if (style === "currency") {
// a. Set internalSlots.[[Currency]] to the result of converting currency to upper case as specified in 6.1.
internalSlots.currency = currency.toUpperCase();
// b. Set internalSlots.[[CurrencyDisplay]] to currencyDisplay.
internalSlots.currencyDisplay = currencyDisplay;
// c. Set internalSlots.[[CurrencySign]] to currencySign.
internalSlots.currencySign = currencySign;
}
// 13. If style is "unit", then
if (style === "unit") {
// a. Set internalSlots.[[Unit]] to unit.
internalSlots.unit = unit;
// b. Set internalSlots.[[UnitDisplay]] to unitDisplay.
internalSlots.unitDisplay = unitDisplay;
}
}

@@ -1,9 +0,9 @@

import { Decimal } from 'decimal.js';
import { RawNumberFormatResult, UnsignedRoundingModeType } from '../types/number.js';
import { Decimal } from "decimal.js";
import { type RawNumberFormatResult, type UnsignedRoundingModeType } from "../types/number.js";
/**
* https://tc39.es/ecma402/#sec-torawfixed
* @param x a finite non-negative Number or BigInt
* @param minFraction an integer between 0 and 20
* @param maxFraction an integer between 0 and 20
*/
* https://tc39.es/ecma402/#sec-torawfixed
* @param x a finite non-negative Number or BigInt
* @param minFraction an integer between 0 and 20
* @param maxFraction an integer between 0 and 20
*/
export declare function ToRawFixed(x: Decimal, minFraction: number, maxFraction: number, roundingIncrement: number, unsignedRoundingMode: UnsignedRoundingModeType): RawNumberFormatResult;

@@ -1,120 +0,116 @@

import { Decimal } from 'decimal.js';
import { repeat } from '../utils.js';
import { ApplyUnsignedRoundingMode } from './ApplyUnsignedRoundingMode.js';
import { getPowerOf10 } from './decimal-cache.js';
import { Decimal } from "decimal.js";
import "../types/number.js";
import { repeat } from "../utils.js";
import { ApplyUnsignedRoundingMode } from "./ApplyUnsignedRoundingMode.js";
import { getPowerOf10 } from "./decimal-cache.js";
//IMPL: Setting Decimal configuration
Decimal.set({
toExpPos: 100,
});
Decimal.set({ toExpPos: 100 });
//IMPL: Helper function to calculate raw fixed value
function ToRawFixedFn(n, f) {
return n.times(getPowerOf10(-f));
return n.times(getPowerOf10(-f));
}
//IMPL: Helper function to find n1 and r1
function findN1R1(x, f, roundingIncrement) {
var nx = x.times(getPowerOf10(f)).floor();
var n1 = nx.div(roundingIncrement).floor().times(roundingIncrement);
var r1 = ToRawFixedFn(n1, f);
return {
n1: n1,
r1: r1,
};
const nx = x.times(getPowerOf10(f)).floor();
const n1 = nx.div(roundingIncrement).floor().times(roundingIncrement);
const r1 = ToRawFixedFn(n1, f);
return {
n1,
r1
};
}
//IMPL: Helper function to find n2 and r2
function findN2R2(x, f, roundingIncrement) {
var nx = x.times(getPowerOf10(f)).ceil();
var n2 = nx.div(roundingIncrement).ceil().times(roundingIncrement);
var r2 = ToRawFixedFn(n2, f);
return {
n2: n2,
r2: r2,
};
const nx = x.times(getPowerOf10(f)).ceil();
const n2 = nx.div(roundingIncrement).ceil().times(roundingIncrement);
const r2 = ToRawFixedFn(n2, f);
return {
n2,
r2
};
}
/**
* https://tc39.es/ecma402/#sec-torawfixed
* @param x a finite non-negative Number or BigInt
* @param minFraction an integer between 0 and 20
* @param maxFraction an integer between 0 and 20
*/
* https://tc39.es/ecma402/#sec-torawfixed
* @param x a finite non-negative Number or BigInt
* @param minFraction an integer between 0 and 20
* @param maxFraction an integer between 0 and 20
*/
export function ToRawFixed(x, minFraction, maxFraction, roundingIncrement, unsignedRoundingMode) {
// 1. Let f be maxFraction.
var f = maxFraction;
// 2. Let n1 and r1 be the results of performing the maximized rounding of x to f fraction digits.
var _a = findN1R1(x, f, roundingIncrement), n1 = _a.n1, r1 = _a.r1;
// 3. Let n2 and r2 be the results of performing the minimized rounding of x to f fraction digits.
var _b = findN2R2(x, f, roundingIncrement), n2 = _b.n2, r2 = _b.r2;
// 4. Let r be ApplyUnsignedRoundingMode(x, r1, r2, unsignedRoundingMode).
var r = ApplyUnsignedRoundingMode(x, r1, r2, unsignedRoundingMode);
var n, xFinal;
var m;
// 5. If r is equal to r1, then
if (r.eq(r1)) {
// a. Let n be n1.
n = n1;
// b. Let xFinal be r1.
xFinal = r1;
}
else {
// 6. Else,
// a. Let n be n2.
n = n2;
// b. Let xFinal be r2.
xFinal = r2;
}
// 7. If n is 0, let m be "0".
if (n.isZero()) {
m = '0';
}
else {
// 8. Else, let m be the String representation of n.
m = n.toString();
}
var int;
// 9. If f is not 0, then
if (f !== 0) {
// a. Let k be the length of m.
var k = m.length;
// b. If k < f, then
if (k <= f) {
// i. Let z be the String value consisting of f + 1 - k occurrences of the character "0".
var z = repeat('0', f - k + 1);
// ii. Set m to the string-concatenation of z and m.
m = z + m;
// iii. Set k to f + 1.
k = f + 1;
}
// c. Let a be the substring of m from 0 to k - f.
var a = m.slice(0, k - f);
// d. Let b be the substring of m from k - f to k.
var b = m.slice(m.length - f);
// e. Set m to the string-concatenation of a, ".", and b.
m = a + '.' + b;
// f. Let int be the length of a.
int = a.length;
}
else {
// 10. Else, let int be the length of m.
int = m.length;
}
// 11. Let cut be maxFraction - minFraction.
var cut = maxFraction - minFraction;
// 12. Repeat, while cut > 0 and the last character of m is "0",
while (cut > 0 && m[m.length - 1] === '0') {
// a. Remove the last character from m.
m = m.slice(0, m.length - 1);
// b. Decrease cut by 1.
cut--;
}
// 13. If the last character of m is ".", then
if (m[m.length - 1] === '\u002e') {
// a. Remove the last character from m.
m = m.slice(0, m.length - 1);
}
// 14. Return the Record { [[FormattedString]]: m, [[RoundedNumber]]: xFinal, [[IntegerDigitsCount]]: int, [[RoundingMagnitude]]: -f }.
return {
formattedString: m,
roundedNumber: xFinal,
integerDigitsCount: int,
roundingMagnitude: -f,
};
// 1. Let f be maxFraction.
const f = maxFraction;
// 2. Let n1 and r1 be the results of performing the maximized rounding of x to f fraction digits.
const { n1, r1 } = findN1R1(x, f, roundingIncrement);
// 3. Let n2 and r2 be the results of performing the minimized rounding of x to f fraction digits.
const { n2, r2 } = findN2R2(x, f, roundingIncrement);
// 4. Let r be ApplyUnsignedRoundingMode(x, r1, r2, unsignedRoundingMode).
const r = ApplyUnsignedRoundingMode(x, r1, r2, unsignedRoundingMode);
let n, xFinal;
let m;
// 5. If r is equal to r1, then
if (r.eq(r1)) {
// a. Let n be n1.
n = n1;
// b. Let xFinal be r1.
xFinal = r1;
} else {
// 6. Else,
// a. Let n be n2.
n = n2;
// b. Let xFinal be r2.
xFinal = r2;
}
// 7. If n is 0, let m be "0".
if (n.isZero()) {
m = "0";
} else {
// 8. Else, let m be the String representation of n.
m = n.toString();
}
let int;
// 9. If f is not 0, then
if (f !== 0) {
// a. Let k be the length of m.
let k = m.length;
// b. If k < f, then
if (k <= f) {
// i. Let z be the String value consisting of f + 1 - k occurrences of the character "0".
const z = repeat("0", f - k + 1);
// ii. Set m to the string-concatenation of z and m.
m = z + m;
// iii. Set k to f + 1.
k = f + 1;
}
// c. Let a be the substring of m from 0 to k - f.
const a = m.slice(0, k - f);
// d. Let b be the substring of m from k - f to k.
const b = m.slice(m.length - f);
// e. Set m to the string-concatenation of a, ".", and b.
m = a + "." + b;
// f. Let int be the length of a.
int = a.length;
} else {
// 10. Else, let int be the length of m.
int = m.length;
}
// 11. Let cut be maxFraction - minFraction.
let cut = maxFraction - minFraction;
// 12. Repeat, while cut > 0 and the last character of m is "0",
while (cut > 0 && m[m.length - 1] === "0") {
// a. Remove the last character from m.
m = m.slice(0, m.length - 1);
// b. Decrease cut by 1.
cut--;
}
// 13. If the last character of m is ".", then
if (m[m.length - 1] === ".") {
// a. Remove the last character from m.
m = m.slice(0, m.length - 1);
}
// 14. Return the Record { [[FormattedString]]: m, [[RoundedNumber]]: xFinal, [[IntegerDigitsCount]]: int, [[RoundingMagnitude]]: -f }.
return {
formattedString: m,
roundedNumber: xFinal,
integerDigitsCount: int,
roundingMagnitude: -f
};
}

@@ -1,9 +0,9 @@

import { Decimal } from 'decimal.js';
import { RawNumberFormatResult, UnsignedRoundingModeType } from '../types/number.js';
import type { Decimal } from "decimal.js";
import { type RawNumberFormatResult, type UnsignedRoundingModeType } from "../types/number.js";
/**
* https://tc39.es/ecma402/#sec-torawprecision
* @param x a finite non-negative Number or BigInt
* @param minPrecision an integer between 1 and 21
* @param maxPrecision an integer between 1 and 21
*/
* https://tc39.es/ecma402/#sec-torawprecision
* @param x a finite non-negative Number or BigInt
* @param minPrecision an integer between 1 and 21
* @param maxPrecision an integer between 1 and 21
*/
export declare function ToRawPrecision(x: Decimal, minPrecision: number, maxPrecision: number, unsignedRoundingMode: UnsignedRoundingModeType): RawNumberFormatResult;

@@ -1,211 +0,208 @@

import { ZERO } from '../constants.js';
import { invariant, repeat } from '../utils.js';
import { ApplyUnsignedRoundingMode } from './ApplyUnsignedRoundingMode.js';
import { getPowerOf10 } from './decimal-cache.js';
import { ZERO } from "../constants.js";
import "../types/number.js";
import { invariant, repeat } from "../utils.js";
import { ApplyUnsignedRoundingMode } from "./ApplyUnsignedRoundingMode.js";
import { getPowerOf10 } from "./decimal-cache.js";
//IMPL: Helper function to find n1, e1, and r1 using direct calculation
function findN1E1R1(x, p) {
var maxN1 = getPowerOf10(p);
var minN1 = getPowerOf10(p - 1);
// Direct calculation: compute e1 from logarithm
// e1 is the exponent such that n1 * 10^(e1-p+1) <= x
// Taking log: log(n1) + (e1-p+1)*log(10) <= log(x)
// Since n1 is between 10^(p-1) and 10^p, we have:
// (p-1) + (e1-p+1) <= log10(x) < p + (e1-p+1)
// Simplifying: e1 <= log10(x) < e1 + 1
// Therefore: e1 = floor(log10(x))
var log10x = x.log(10);
var e1 = log10x.floor();
// Calculate n1 and r1 from e1
var divisor = getPowerOf10(e1.minus(p).plus(1));
var n1 = x.div(divisor).floor();
var r1 = n1.times(divisor);
// Verify and adjust if n1 is out of bounds
// This handles edge cases near powers of 10
if (n1.greaterThanOrEqualTo(maxN1)) {
e1 = e1.plus(1);
var newDivisor = getPowerOf10(e1.minus(p).plus(1));
n1 = x.div(newDivisor).floor();
r1 = n1.times(newDivisor);
}
else if (n1.lessThan(minN1)) {
e1 = e1.minus(1);
var newDivisor = getPowerOf10(e1.minus(p).plus(1));
n1 = x.div(newDivisor).floor();
r1 = n1.times(newDivisor);
}
// Final verification with fallback to iterative search if needed
if (r1.lessThanOrEqualTo(x) &&
n1.lessThan(maxN1) &&
n1.greaterThanOrEqualTo(minN1)) {
return { n1: n1, e1: e1, r1: r1 };
}
// Fallback: iterative search (should rarely be needed)
var maxE1 = x.div(minN1).log(10).plus(p).minus(1).ceil();
var currentE1 = maxE1;
while (true) {
var currentDivisor = getPowerOf10(currentE1.minus(p).plus(1));
var currentN1 = x.div(currentDivisor).floor();
if (currentN1.lessThan(maxN1) && currentN1.greaterThanOrEqualTo(minN1)) {
var currentR1 = currentN1.times(currentDivisor);
if (currentR1.lessThanOrEqualTo(x)) {
return {
n1: currentN1,
e1: currentE1,
r1: currentR1,
};
}
}
currentE1 = currentE1.minus(1);
}
const maxN1 = getPowerOf10(p);
const minN1 = getPowerOf10(p - 1);
// Direct calculation: compute e1 from logarithm
// e1 is the exponent such that n1 * 10^(e1-p+1) <= x
// Taking log: log(n1) + (e1-p+1)*log(10) <= log(x)
// Since n1 is between 10^(p-1) and 10^p, we have:
// (p-1) + (e1-p+1) <= log10(x) < p + (e1-p+1)
// Simplifying: e1 <= log10(x) < e1 + 1
// Therefore: e1 = floor(log10(x))
const log10x = x.log(10);
let e1 = log10x.floor();
// Calculate n1 and r1 from e1
const divisor = getPowerOf10(e1.minus(p).plus(1));
let n1 = x.div(divisor).floor();
let r1 = n1.times(divisor);
// Verify and adjust if n1 is out of bounds
// This handles edge cases near powers of 10
if (n1.greaterThanOrEqualTo(maxN1)) {
e1 = e1.plus(1);
const newDivisor = getPowerOf10(e1.minus(p).plus(1));
n1 = x.div(newDivisor).floor();
r1 = n1.times(newDivisor);
} else if (n1.lessThan(minN1)) {
e1 = e1.minus(1);
const newDivisor = getPowerOf10(e1.minus(p).plus(1));
n1 = x.div(newDivisor).floor();
r1 = n1.times(newDivisor);
}
// Final verification with fallback to iterative search if needed
if (r1.lessThanOrEqualTo(x) && n1.lessThan(maxN1) && n1.greaterThanOrEqualTo(minN1)) {
return {
n1,
e1,
r1
};
}
// Fallback: iterative search (should rarely be needed)
const maxE1 = x.div(minN1).log(10).plus(p).minus(1).ceil();
let currentE1 = maxE1;
while (true) {
const currentDivisor = getPowerOf10(currentE1.minus(p).plus(1));
let currentN1 = x.div(currentDivisor).floor();
if (currentN1.lessThan(maxN1) && currentN1.greaterThanOrEqualTo(minN1)) {
const currentR1 = currentN1.times(currentDivisor);
if (currentR1.lessThanOrEqualTo(x)) {
return {
n1: currentN1,
e1: currentE1,
r1: currentR1
};
}
}
currentE1 = currentE1.minus(1);
}
}
//IMPL: Helper function to find n2, e2, and r2 using direct calculation
function findN2E2R2(x, p) {
var maxN2 = getPowerOf10(p);
var minN2 = getPowerOf10(p - 1);
// Direct calculation: similar to findN1E1R1 but with ceiling
var log10x = x.log(10);
var e2 = log10x.floor();
// Calculate n2 and r2 from e2
var divisor = getPowerOf10(e2.minus(p).plus(1));
var n2 = x.div(divisor).ceil();
var r2 = n2.times(divisor);
// Verify and adjust if n2 is out of bounds
if (n2.greaterThanOrEqualTo(maxN2)) {
e2 = e2.plus(1);
var newDivisor = getPowerOf10(e2.minus(p).plus(1));
n2 = x.div(newDivisor).ceil();
r2 = n2.times(newDivisor);
}
else if (n2.lessThan(minN2)) {
e2 = e2.minus(1);
var newDivisor = getPowerOf10(e2.minus(p).plus(1));
n2 = x.div(newDivisor).ceil();
r2 = n2.times(newDivisor);
}
// Final verification with fallback to iterative search if needed
if (r2.greaterThanOrEqualTo(x) &&
n2.lessThan(maxN2) &&
n2.greaterThanOrEqualTo(minN2)) {
return { n2: n2, e2: e2, r2: r2 };
}
// Fallback: iterative search (should rarely be needed)
var minE2 = x.div(maxN2).log(10).plus(p).minus(1).floor();
var currentE2 = minE2;
while (true) {
var currentDivisor = getPowerOf10(currentE2.minus(p).plus(1));
var currentN2 = x.div(currentDivisor).ceil();
if (currentN2.lessThan(maxN2) && currentN2.greaterThanOrEqualTo(minN2)) {
var currentR2 = currentN2.times(currentDivisor);
if (currentR2.greaterThanOrEqualTo(x)) {
return {
n2: currentN2,
e2: currentE2,
r2: currentR2,
};
}
}
currentE2 = currentE2.plus(1);
}
const maxN2 = getPowerOf10(p);
const minN2 = getPowerOf10(p - 1);
// Direct calculation: similar to findN1E1R1 but with ceiling
const log10x = x.log(10);
let e2 = log10x.floor();
// Calculate n2 and r2 from e2
const divisor = getPowerOf10(e2.minus(p).plus(1));
let n2 = x.div(divisor).ceil();
let r2 = n2.times(divisor);
// Verify and adjust if n2 is out of bounds
if (n2.greaterThanOrEqualTo(maxN2)) {
e2 = e2.plus(1);
const newDivisor = getPowerOf10(e2.minus(p).plus(1));
n2 = x.div(newDivisor).ceil();
r2 = n2.times(newDivisor);
} else if (n2.lessThan(minN2)) {
e2 = e2.minus(1);
const newDivisor = getPowerOf10(e2.minus(p).plus(1));
n2 = x.div(newDivisor).ceil();
r2 = n2.times(newDivisor);
}
// Final verification with fallback to iterative search if needed
if (r2.greaterThanOrEqualTo(x) && n2.lessThan(maxN2) && n2.greaterThanOrEqualTo(minN2)) {
return {
n2,
e2,
r2
};
}
// Fallback: iterative search (should rarely be needed)
const minE2 = x.div(maxN2).log(10).plus(p).minus(1).floor();
let currentE2 = minE2;
while (true) {
const currentDivisor = getPowerOf10(currentE2.minus(p).plus(1));
let currentN2 = x.div(currentDivisor).ceil();
if (currentN2.lessThan(maxN2) && currentN2.greaterThanOrEqualTo(minN2)) {
const currentR2 = currentN2.times(currentDivisor);
if (currentR2.greaterThanOrEqualTo(x)) {
return {
n2: currentN2,
e2: currentE2,
r2: currentR2
};
}
}
currentE2 = currentE2.plus(1);
}
}
/**
* https://tc39.es/ecma402/#sec-torawprecision
* @param x a finite non-negative Number or BigInt
* @param minPrecision an integer between 1 and 21
* @param maxPrecision an integer between 1 and 21
*/
* https://tc39.es/ecma402/#sec-torawprecision
* @param x a finite non-negative Number or BigInt
* @param minPrecision an integer between 1 and 21
* @param maxPrecision an integer between 1 and 21
*/
export function ToRawPrecision(x, minPrecision, maxPrecision, unsignedRoundingMode) {
// 1. Let p be maxPrecision.
var p = maxPrecision;
var m;
var e;
var xFinal;
// 2. If x = 0, then
if (x.isZero()) {
// a. Let m be the String value consisting of p occurrences of the character "0".
m = repeat('0', p);
// b. Let e be 0.
e = 0;
// c. Let xFinal be 0.
xFinal = ZERO;
}
else {
// 3. Else,
// a. Let {n1, e1, r1} be the result of findN1E1R1(x, p).
var _a = findN1E1R1(x, p), n1 = _a.n1, e1 = _a.e1, r1 = _a.r1;
// b. Let {n2, e2, r2} be the result of findN2E2R2(x, p).
var _b = findN2E2R2(x, p), n2 = _b.n2, e2 = _b.e2, r2 = _b.r2;
// c. Let r be ApplyUnsignedRoundingMode(x, r1, r2, unsignedRoundingMode).
var r = ApplyUnsignedRoundingMode(x, r1, r2, unsignedRoundingMode);
var n
// d. If r = r1, then
= void 0;
// d. If r = r1, then
if (r.eq(r1)) {
// i. Let n be n1.
n = n1;
// ii. Let e be e1.
e = e1.toNumber();
// iii. Let xFinal be r1.
xFinal = r1;
}
else {
// e. Else,
// i. Let n be n2.
n = n2;
// ii. Let e be e2.
e = e2.toNumber();
// iii. Let xFinal be r2.
xFinal = r2;
}
// f. Let m be the String representation of n.
m = n.toString();
}
var int;
// 4. If e ≥ p - 1, then
if (e >= p - 1) {
// a. Let m be the string-concatenation of m and p - 1 - e occurrences of the character "0".
m = m + repeat('0', e - p + 1);
// b. Let int be e + 1.
int = e + 1;
}
else if (e >= 0) {
// 5. Else if e ≥ 0, then
// a. Let m be the string-concatenation of the first e + 1 characters of m, ".", and the remaining p - (e + 1) characters of m.
m = m.slice(0, e + 1) + '.' + m.slice(m.length - (p - (e + 1)));
// b. Let int be e + 1.
int = e + 1;
}
else {
// 6. Else,
// a. Assert: e < 0.
invariant(e < 0, 'e should be less than 0');
// b. Let m be the string-concatenation of "0.", -e - 1 occurrences of the character "0", and m.
m = '0.' + repeat('0', -e - 1) + m;
// c. Let int be 1.
int = 1;
}
// 7. If m contains ".", and maxPrecision > minPrecision, then
if (m.includes('.') && maxPrecision > minPrecision) {
// a. Let cut be maxPrecision - minPrecision.
var cut = maxPrecision - minPrecision;
// b. Repeat, while cut > 0 and the last character of m is "0",
while (cut > 0 && m[m.length - 1] === '0') {
// i. Remove the last character from m.
m = m.slice(0, m.length - 1);
// ii. Decrease cut by 1.
cut--;
}
// c. If the last character of m is ".", then
if (m[m.length - 1] === '.') {
// i. Remove the last character from m.
m = m.slice(0, m.length - 1);
}
}
// 8. Return the Record { [[FormattedString]]: m, [[RoundedNumber]]: xFinal, [[IntegerDigitsCount]]: int, [[RoundingMagnitude]]: e }.
return {
formattedString: m,
roundedNumber: xFinal,
integerDigitsCount: int,
roundingMagnitude: e,
};
// 1. Let p be maxPrecision.
const p = maxPrecision;
let m;
let e;
let xFinal;
// 2. If x = 0, then
if (x.isZero()) {
// a. Let m be the String value consisting of p occurrences of the character "0".
m = repeat("0", p);
// b. Let e be 0.
e = 0;
// c. Let xFinal be 0.
xFinal = ZERO;
} else {
// 3. Else,
// a. Let {n1, e1, r1} be the result of findN1E1R1(x, p).
const { n1, e1, r1 } = findN1E1R1(x, p);
// b. Let {n2, e2, r2} be the result of findN2E2R2(x, p).
const { n2, e2, r2 } = findN2E2R2(x, p);
// c. Let r be ApplyUnsignedRoundingMode(x, r1, r2, unsignedRoundingMode).
let r = ApplyUnsignedRoundingMode(x, r1, r2, unsignedRoundingMode);
let n;
// d. If r = r1, then
if (r.eq(r1)) {
// i. Let n be n1.
n = n1;
// ii. Let e be e1.
e = e1.toNumber();
// iii. Let xFinal be r1.
xFinal = r1;
} else {
// e. Else,
// i. Let n be n2.
n = n2;
// ii. Let e be e2.
e = e2.toNumber();
// iii. Let xFinal be r2.
xFinal = r2;
}
// f. Let m be the String representation of n.
m = n.toString();
}
let int;
// 4. If e ≥ p - 1, then
if (e >= p - 1) {
// a. Let m be the string-concatenation of m and p - 1 - e occurrences of the character "0".
m = m + repeat("0", e - p + 1);
// b. Let int be e + 1.
int = e + 1;
} else if (e >= 0) {
// 5. Else if e ≥ 0, then
// a. Let m be the string-concatenation of the first e + 1 characters of m, ".", and the remaining p - (e + 1) characters of m.
m = m.slice(0, e + 1) + "." + m.slice(m.length - (p - (e + 1)));
// b. Let int be e + 1.
int = e + 1;
} else {
// 6. Else,
// a. Assert: e < 0.
invariant(e < 0, "e should be less than 0");
// b. Let m be the string-concatenation of "0.", -e - 1 occurrences of the character "0", and m.
m = "0." + repeat("0", -e - 1) + m;
// c. Let int be 1.
int = 1;
}
// 7. If m contains ".", and maxPrecision > minPrecision, then
if (m.includes(".") && maxPrecision > minPrecision) {
// a. Let cut be maxPrecision - minPrecision.
let cut = maxPrecision - minPrecision;
// b. Repeat, while cut > 0 and the last character of m is "0",
while (cut > 0 && m[m.length - 1] === "0") {
// i. Remove the last character from m.
m = m.slice(0, m.length - 1);
// ii. Decrease cut by 1.
cut--;
}
// c. If the last character of m is ".", then
if (m[m.length - 1] === ".") {
// i. Remove the last character from m.
m = m.slice(0, m.length - 1);
}
}
// 8. Return the Record { [[FormattedString]]: m, [[RoundedNumber]]: xFinal, [[IntegerDigitsCount]]: int, [[RoundingMagnitude]]: e }.
return {
formattedString: m,
roundedNumber: xFinal,
integerDigitsCount: int,
roundingMagnitude: e
};
}
{
"name": "@formatjs/ecma402-abstract",
"description": "A collection of implementation for ECMAScript abstract operations",
"version": "3.0.7",
"version": "3.0.8",
"license": "MIT",

@@ -16,4 +16,4 @@ "author": "Long Ho <holevietlong@gmail.com",

"tslib": "^2.8.0",
"@formatjs/intl-localematcher": "0.7.4",
"@formatjs/fast-memoize": "3.0.2"
"@formatjs/fast-memoize": "3.0.3",
"@formatjs/intl-localematcher": "0.7.5"
},

@@ -20,0 +20,0 @@ "bugs": "https://github.com/formatjs/formatjs/issues",

/**
* Partition a pattern into a list of literals and placeholders
* https://tc39.es/ecma402/#sec-partitionpattern
* @param pattern
*/
* Partition a pattern into a list of literals and placeholders
* https://tc39.es/ecma402/#sec-partitionpattern
* @param pattern
*/
export declare function PartitionPattern<T extends string>(pattern: string): Array<{
type: T;
value: string | undefined;
type: T;
value: string | undefined;
}>;

@@ -1,36 +0,36 @@

import { invariant } from './utils.js';
import { invariant } from "./utils.js";
/**
* Partition a pattern into a list of literals and placeholders
* https://tc39.es/ecma402/#sec-partitionpattern
* @param pattern
*/
* Partition a pattern into a list of literals and placeholders
* https://tc39.es/ecma402/#sec-partitionpattern
* @param pattern
*/
export function PartitionPattern(pattern) {
var result = [];
var beginIndex = pattern.indexOf('{');
var endIndex = 0;
var nextIndex = 0;
var length = pattern.length;
while (beginIndex < pattern.length && beginIndex > -1) {
endIndex = pattern.indexOf('}', beginIndex);
invariant(endIndex > beginIndex, "Invalid pattern ".concat(pattern));
if (beginIndex > nextIndex) {
result.push({
type: 'literal',
value: pattern.substring(nextIndex, beginIndex),
});
}
result.push({
type: pattern.substring(beginIndex + 1, endIndex),
value: undefined,
});
nextIndex = endIndex + 1;
beginIndex = pattern.indexOf('{', nextIndex);
}
if (nextIndex < length) {
result.push({
type: 'literal',
value: pattern.substring(nextIndex, length),
});
}
return result;
const result = [];
let beginIndex = pattern.indexOf("{");
let endIndex = 0;
let nextIndex = 0;
const length = pattern.length;
while (beginIndex < pattern.length && beginIndex > -1) {
endIndex = pattern.indexOf("}", beginIndex);
invariant(endIndex > beginIndex, `Invalid pattern ${pattern}`);
if (beginIndex > nextIndex) {
result.push({
type: "literal",
value: pattern.substring(nextIndex, beginIndex)
});
}
result.push({
type: pattern.substring(beginIndex + 1, endIndex),
value: undefined
});
nextIndex = endIndex + 1;
beginIndex = pattern.indexOf("{", nextIndex);
}
if (nextIndex < length) {
result.push({
type: "literal",
value: pattern.substring(nextIndex, length)
});
}
return result;
}

@@ -0,1 +1,2 @@

// @generated from regex-gen.ts
export declare const S_UNICODE_REGEX: RegExp;
// @generated from regex-gen.ts
export var S_UNICODE_REGEX = /[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u166D\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20BF\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2E50\u2E51\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uAB6A\uAB6B\uFB29\uFBB2-\uFBC1\uFDFC\uFDFD\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD805\uDF3F|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDE8\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED7\uDEE0-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF73\uDF80-\uDFD8\uDFE0-\uDFEB]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDD78\uDD7A-\uDDCB\uDDCD-\uDE53\uDE60-\uDE6D\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6\uDF00-\uDF92\uDF94-\uDFCA]/;
export const S_UNICODE_REGEX = /[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u166D\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20BF\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2E50\u2E51\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uAB6A\uAB6B\uFB29\uFBB2-\uFBC1\uFDFC\uFDFD\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD805\uDF3F|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDE8\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED7\uDEE0-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF73\uDF80-\uDFD8\uDFE0-\uDFEB]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDD78\uDD7A-\uDDCB\uDDCD-\uDE53\uDE60-\uDE6D\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6\uDF00-\uDF92\uDF94-\uDFCA]/;
/**
* https://tc39.es/ecma402/#sec-supportedlocales
* @param availableLocales
* @param requestedLocales
* @param options
*/
* https://tc39.es/ecma402/#sec-supportedlocales
* @param availableLocales
* @param requestedLocales
* @param options
*/
export declare function SupportedLocales(availableLocales: Set<string>, requestedLocales: string[], options?: {
localeMatcher?: 'best fit' | 'lookup';
localeMatcher?: "best fit" | "lookup";
}): string[];

@@ -1,20 +0,20 @@

import { LookupSupportedLocales } from '@formatjs/intl-localematcher';
import { ToObject } from './262.js';
import { GetOption } from './GetOption.js';
import { LookupSupportedLocales } from "@formatjs/intl-localematcher";
import { ToObject } from "./262.js";
import { GetOption } from "./GetOption.js";
/**
* https://tc39.es/ecma402/#sec-supportedlocales
* @param availableLocales
* @param requestedLocales
* @param options
*/
* https://tc39.es/ecma402/#sec-supportedlocales
* @param availableLocales
* @param requestedLocales
* @param options
*/
export function SupportedLocales(availableLocales, requestedLocales, options) {
var matcher = 'best fit';
if (options !== undefined) {
options = ToObject(options);
matcher = GetOption(options, 'localeMatcher', 'string', ['lookup', 'best fit'], 'best fit');
}
if (matcher === 'best fit') {
return LookupSupportedLocales(Array.from(availableLocales), requestedLocales);
}
return LookupSupportedLocales(Array.from(availableLocales), requestedLocales);
let matcher = "best fit";
if (options !== undefined) {
options = ToObject(options);
matcher = GetOption(options, "localeMatcher", "string", ["lookup", "best fit"], "best fit");
}
if (matcher === "best fit") {
return LookupSupportedLocales(Array.from(availableLocales), requestedLocales);
}
return LookupSupportedLocales(Array.from(availableLocales), requestedLocales);
}

@@ -1,2 +0,2 @@

import { Decimal } from 'decimal.js';
import { Decimal } from "decimal.js";
export declare function ToIntlMathematicalValue(input: unknown): Decimal;

@@ -1,27 +0,26 @@

import { Decimal } from 'decimal.js';
import { ToPrimitive } from './262.js';
import { Decimal } from "decimal.js";
import { ToPrimitive } from "./262.js";
export function ToIntlMathematicalValue(input) {
var primValue = ToPrimitive(input, 'number');
if (typeof primValue === 'bigint') {
return new Decimal(primValue);
}
// IMPL
if (primValue === undefined) {
return new Decimal(NaN);
}
if (primValue === true) {
return new Decimal(1);
}
if (primValue === false) {
return new Decimal(0);
}
if (primValue === null) {
return new Decimal(0);
}
try {
return new Decimal(primValue);
}
catch (_a) {
return new Decimal(NaN);
}
let primValue = ToPrimitive(input, "number");
if (typeof primValue === "bigint") {
return new Decimal(primValue);
}
// IMPL
if (primValue === undefined) {
return new Decimal(NaN);
}
if (primValue === true) {
return new Decimal(1);
}
if (primValue === false) {
return new Decimal(0);
}
if (primValue === null) {
return new Decimal(0);
}
try {
return new Decimal(primValue);
} catch {
return new Decimal(NaN);
}
}
export type Locale = string;
export interface LocaleData<T> {
data: T;
locale: Locale;
data: T;
locale: Locale;
}
export interface LookupMatcherResult {
locale: string;
extension?: string;
nu?: string;
locale: string;
extension?: string;
nu?: string;
}

@@ -1,149 +0,144 @@

export type Formats = Pick<Intl.DateTimeFormatOptions, 'weekday' | 'era' | 'year' | 'month' | 'day' | 'dayPeriod' | 'hour' | 'minute' | 'second' | 'timeZoneName'> & {
fractionalSecondDigits?: 1 | 2 | 3;
hour12?: boolean;
pattern: string;
pattern12: string;
skeleton: string;
rawPattern: string;
rangePatterns: Record<TABLE_2 | 'default', RangePatterns>;
rangePatterns12: Record<TABLE_2 | 'default', RangePatterns>;
export type Formats = Pick<Intl.DateTimeFormatOptions, "weekday" | "era" | "year" | "month" | "day" | "dayPeriod" | "hour" | "minute" | "second" | "timeZoneName"> & {
fractionalSecondDigits?: 1 | 2 | 3;
hour12?: boolean;
pattern: string;
pattern12: string;
skeleton: string;
rawPattern: string;
rangePatterns: Record<TABLE_2 | "default", RangePatterns>;
rangePatterns12: Record<TABLE_2 | "default", RangePatterns>;
};
export interface IntlDateTimeFormatInternal {
locale: string;
dataLocale: string;
calendar?: string;
dateStyle?: 'full' | 'long' | 'medium' | 'short';
timeStyle?: 'full' | 'long' | 'medium' | 'short';
weekday: 'narrow' | 'short' | 'long';
era: 'narrow' | 'short' | 'long';
year: '2-digit' | 'numeric';
month: '2-digit' | 'numeric' | 'narrow' | 'short' | 'long';
day: '2-digit' | 'numeric';
dayPeriod: 'narrow' | 'short' | 'long';
hour: '2-digit' | 'numeric';
minute: '2-digit' | 'numeric';
second: '2-digit' | 'numeric';
timeZoneName: 'short' | 'long' | 'shortOffset' | 'longOffset' | 'shortGeneric' | 'longGeneric';
fractionalSecondDigits?: 1 | 2 | 3;
hourCycle: string;
numberingSystem: string;
timeZone: string;
pattern: string;
format: Formats;
rangePatterns: Record<TABLE_2 | 'default', RangePatterns>;
boundFormat?: Intl.DateTimeFormat['format'];
locale: string;
dataLocale: string;
calendar?: string;
dateStyle?: "full" | "long" | "medium" | "short";
timeStyle?: "full" | "long" | "medium" | "short";
weekday: "narrow" | "short" | "long";
era: "narrow" | "short" | "long";
year: "2-digit" | "numeric";
month: "2-digit" | "numeric" | "narrow" | "short" | "long";
day: "2-digit" | "numeric";
dayPeriod: "narrow" | "short" | "long";
hour: "2-digit" | "numeric";
minute: "2-digit" | "numeric";
second: "2-digit" | "numeric";
timeZoneName: "short" | "long" | "shortOffset" | "longOffset" | "shortGeneric" | "longGeneric";
fractionalSecondDigits?: 1 | 2 | 3;
hourCycle: string;
numberingSystem: string;
timeZone: string;
pattern: string;
format: Formats;
rangePatterns: Record<TABLE_2 | "default", RangePatterns>;
boundFormat?: Intl.DateTimeFormat["format"];
}
export interface RangePatternPart<T extends RangePatternType = RangePatternType> {
source: T;
pattern: string;
source: T;
pattern: string;
}
export type RangePatterns = Pick<Intl.DateTimeFormatOptions, 'weekday' | 'era' | 'year' | 'month' | 'day' | 'hour' | 'minute' | 'second' | 'timeZoneName'> & {
hour12?: boolean;
patternParts: Array<RangePatternPart>;
export type RangePatterns = Pick<Intl.DateTimeFormatOptions, "weekday" | "era" | "year" | "month" | "day" | "hour" | "minute" | "second" | "timeZoneName"> & {
hour12?: boolean;
patternParts: Array<RangePatternPart>;
};
export declare enum RangePatternType {
startRange = "startRange",
shared = "shared",
endRange = "endRange"
startRange = "startRange",
shared = "shared",
endRange = "endRange"
}
export type TABLE_6 = 'weekday' | 'era' | 'year' | 'month' | 'day' | 'dayPeriod' | 'hour' | 'minute' | 'second' | 'fractionalSecondDigits' | 'timeZoneName';
export type TABLE_2 = 'era' | 'year' | 'month' | 'day' | 'dayPeriod' | 'ampm' | 'hour' | 'minute' | 'second' | 'fractionalSecondDigits';
export type TABLE_6 = "weekday" | "era" | "year" | "month" | "day" | "dayPeriod" | "hour" | "minute" | "second" | "fractionalSecondDigits" | "timeZoneName";
export type TABLE_2 = "era" | "year" | "month" | "day" | "dayPeriod" | "ampm" | "hour" | "minute" | "second" | "fractionalSecondDigits";
export type TimeZoneNameData = Record<string, {
long?: [string, string];
short?: [string, string];
long?: [string, string];
short?: [string, string];
}>;
export interface EraData {
BC: string;
AD: string;
BC: string;
AD: string;
}
export interface DateTimeFormatLocaleInternalData {
am: string;
pm: string;
weekday: {
narrow: string[];
long: string[];
short: string[];
};
era: {
narrow: EraData;
long: EraData;
short: EraData;
};
month: {
narrow: string[];
long: string[];
short: string[];
};
/**
* Stand-alone month names (used when month appears without other date fields)
* Falls back to format month if not provided
*/
monthStandalone?: {
narrow: string[];
long: string[];
short: string[];
};
timeZoneName: TimeZoneNameData;
/**
* So we can construct GMT+08:00
*/
gmtFormat: string;
/**
* So we can construct GMT+08:00
*/
hourFormat: string;
hourCycle: string;
dateFormat: {
full: Formats;
long: Formats;
medium: Formats;
short: Formats;
};
timeFormat: {
full: Formats;
long: Formats;
medium: Formats;
short: Formats;
};
dateTimeFormat: {
full: string;
long: string;
medium: string;
short: string;
};
/**
* Interval format fallback pattern from CLDR (e.g., "{0} – {1}" for English, "{0}~{1}" for Japanese)
* Used when no specific interval format is available for a given skeleton
*/
intervalFormatFallback: string;
formats: Record<string, Formats[]>;
nu: string[];
hc: string[];
ca: string[];
am: string;
pm: string;
weekday: {
narrow: string[];
long: string[];
short: string[];
};
era: {
narrow: EraData;
long: EraData;
short: EraData;
};
month: {
narrow: string[];
long: string[];
short: string[];
};
/**
* Stand-alone month names (used when month appears without other date fields)
* Falls back to format month if not provided
*/
monthStandalone?: {
narrow: string[];
long: string[];
short: string[];
};
timeZoneName: TimeZoneNameData;
/**
* So we can construct GMT+08:00
*/
gmtFormat: string;
/**
* So we can construct GMT+08:00
*/
hourFormat: string;
hourCycle: string;
dateFormat: {
full: Formats;
long: Formats;
medium: Formats;
short: Formats;
};
timeFormat: {
full: Formats;
long: Formats;
medium: Formats;
short: Formats;
};
dateTimeFormat: {
full: string;
long: string;
medium: string;
short: string;
};
/**
* Interval format fallback pattern from CLDR (e.g., "{0} – {1}" for English, "{0}~{1}" for Japanese)
* Used when no specific interval format is available for a given skeleton
*/
intervalFormatFallback: string;
formats: Record<string, Formats[]>;
nu: string[];
hc: string[];
ca: string[];
}
export type IntervalFormatsData = {
intervalFormatFallback: string;
intervalFormatFallback: string;
} & Record<string, Record<string, string>>;
export interface DateTimeFormat extends Omit<Intl.DateTimeFormat, 'resolvedOptions' | 'formatRange' | 'formatRangeToParts' | 'formatToParts'> {
resolvedOptions(): ResolvedDateTimeFormatOptions;
formatToParts(date?: Date | number): IntlDateTimeFormatPart[];
formatRange(startDate: number | Date, endDate: number | Date): string;
formatRangeToParts(startDate: number | Date, endDate: number | Date): IntlDateTimeFormatPart[];
export interface DateTimeFormat extends Omit<Intl.DateTimeFormat, "resolvedOptions" | "formatRange" | "formatRangeToParts" | "formatToParts"> {
resolvedOptions(): ResolvedDateTimeFormatOptions;
formatToParts(date?: Date | number): IntlDateTimeFormatPart[];
formatRange(startDate: number | Date, endDate: number | Date): string;
formatRangeToParts(startDate: number | Date, endDate: number | Date): IntlDateTimeFormatPart[];
}
export interface ResolvedDateTimeFormatOptions extends Intl.ResolvedDateTimeFormatOptions {
dateStyle?: 'full' | 'long' | 'medium' | 'short';
timeStyle?: 'full' | 'long' | 'medium' | 'short';
numberingSystem: string;
dateStyle?: "full" | "long" | "medium" | "short";
timeStyle?: "full" | "long" | "medium" | "short";
numberingSystem: string;
}
export type UnpackedZoneData = [
number,
string,
number,
boolean
];
export type IntlDateTimeFormatPartType = Intl.DateTimeFormatPartTypes | 'ampm' | 'relatedYear' | 'yearName' | 'unknown' | 'fractionalSecondDigits';
export type UnpackedZoneData = [number, string, number, boolean];
export type IntlDateTimeFormatPartType = Intl.DateTimeFormatPartTypes | "ampm" | "relatedYear" | "yearName" | "unknown" | "fractionalSecondDigits";
export interface IntlDateTimeFormatPart {
type: IntlDateTimeFormatPartType;
value: string | undefined;
source?: RangePatternType;
type: IntlDateTimeFormatPartType;
value: string | undefined;
source?: RangePatternType;
}

@@ -1,6 +0,6 @@

export var RangePatternType;
(function (RangePatternType) {
RangePatternType["startRange"] = "startRange";
RangePatternType["shared"] = "shared";
RangePatternType["endRange"] = "endRange";
})(RangePatternType || (RangePatternType = {}));
export let RangePatternType = /* @__PURE__ */ function(RangePatternType) {
RangePatternType["startRange"] = "startRange";
RangePatternType["shared"] = "shared";
RangePatternType["endRange"] = "endRange";
return RangePatternType;
}({});

@@ -1,2 +0,2 @@

import { LocaleData } from './core.js';
import { type LocaleData } from "./core.js";
type LanguageTag = string;

@@ -9,58 +9,58 @@ type RegionCode = string;

export interface DisplayNamesData {
/**
* Note that for style fields, `short` and `narrow` might not exist.
* At runtime, the fallback order will be narrow -> short -> long.
*/
types: {
/**
* Maps language subtag like `zh-CN` to their display names.
*/
language: {
dialect: {
narrow: Record<LanguageTag, string>;
short: Record<LanguageTag, string>;
long: Record<LanguageTag, string>;
};
standard: {
narrow: Record<LanguageTag, string>;
short: Record<LanguageTag, string>;
long: Record<LanguageTag, string>;
};
};
region: {
narrow: Record<RegionCode, string>;
short: Record<RegionCode, string>;
long: Record<RegionCode, string>;
};
script: {
narrow: Record<ScriptCode, string>;
short: Record<ScriptCode, string>;
long: Record<ScriptCode, string>;
};
currency: {
narrow: Record<CurrencyCode, string>;
short: Record<CurrencyCode, string>;
long: Record<CurrencyCode, string>;
};
calendar: {
narrow: Record<CalendarCode, string>;
short: Record<CalendarCode, string>;
long: Record<CalendarCode, string>;
};
dateTimeField: {
narrow: Record<DateTimeFieldCode, string>;
short: Record<DateTimeFieldCode, string>;
long: Record<DateTimeFieldCode, string>;
};
};
/**
* Not in spec, but we need this to display both language and region in display name.
* e.g. zh-Hans-SG + "{0}({1})" -> 简体中文(新加坡)
* Here {0} is replaced by language display name and {1} is replaced by region display name.
*/
patterns: {
locale: string;
};
/**
* Note that for style fields, `short` and `narrow` might not exist.
* At runtime, the fallback order will be narrow -> short -> long.
*/
types: {
/**
* Maps language subtag like `zh-CN` to their display names.
*/
language: {
dialect: {
narrow: Record<LanguageTag, string>;
short: Record<LanguageTag, string>;
long: Record<LanguageTag, string>;
};
standard: {
narrow: Record<LanguageTag, string>;
short: Record<LanguageTag, string>;
long: Record<LanguageTag, string>;
};
};
region: {
narrow: Record<RegionCode, string>;
short: Record<RegionCode, string>;
long: Record<RegionCode, string>;
};
script: {
narrow: Record<ScriptCode, string>;
short: Record<ScriptCode, string>;
long: Record<ScriptCode, string>;
};
currency: {
narrow: Record<CurrencyCode, string>;
short: Record<CurrencyCode, string>;
long: Record<CurrencyCode, string>;
};
calendar: {
narrow: Record<CalendarCode, string>;
short: Record<CalendarCode, string>;
long: Record<CalendarCode, string>;
};
dateTimeField: {
narrow: Record<DateTimeFieldCode, string>;
short: Record<DateTimeFieldCode, string>;
long: Record<DateTimeFieldCode, string>;
};
};
/**
* Not in spec, but we need this to display both language and region in display name.
* e.g. zh-Hans-SG + "{0}({1})" -> 简体中文(新加坡)
* Here {0} is replaced by language display name and {1} is replaced by region display name.
*/
patterns: {
locale: string;
};
}
export type DisplayNamesLocaleData = LocaleData<DisplayNamesData>;
export {};

@@ -1,1 +0,1 @@

export {};
import "./core.js";

@@ -1,18 +0,18 @@

import { LocaleData } from './core.js';
import { type LocaleData } from "./core.js";
export type ListPatternLocaleData = LocaleData<ListPatternFieldsData>;
export interface ListPatternFieldsData {
conjunction?: ListPatternData;
disjunction?: ListPatternData;
unit?: ListPatternData;
conjunction?: ListPatternData;
disjunction?: ListPatternData;
unit?: ListPatternData;
}
export interface ListPattern {
start: string;
middle: string;
end: string;
pair: string;
start: string;
middle: string;
end: string;
pair: string;
}
export interface ListPatternData {
long: ListPattern;
short?: ListPattern;
narrow?: ListPattern;
long: ListPattern;
short?: ListPattern;
narrow?: ListPattern;
}

@@ -1,1 +0,1 @@

export {};
import "./core.js";

@@ -1,173 +0,187 @@

import { Decimal } from 'decimal.js';
import { LocaleData } from './core.js';
import { LDMLPluralRule } from './plural-rules.js';
export type NumberFormatNotation = 'standard' | 'scientific' | 'engineering' | 'compact';
export type RoundingPriorityType = 'auto' | 'morePrecision' | 'lessPrecision';
export type NumberFormatRoundingType = 'morePrecision' | 'lessPrecision' | 'significantDigits' | 'fractionDigits';
export type RoundingModeType = 'ceil' | 'floor' | 'expand' | 'trunc' | 'halfCeil' | 'halfFloor' | 'halfExpand' | 'halfTrunc' | 'halfEven';
export type UnsignedRoundingModeType = 'infinity' | 'zero' | 'half-infinity' | 'half-zero' | 'half-even';
export type UseGroupingType = 'min2' | 'auto' | 'always' | boolean;
import type { Decimal } from "decimal.js";
import { type LocaleData } from "./core.js";
import { type LDMLPluralRule } from "./plural-rules.js";
export type NumberFormatNotation = "standard" | "scientific" | "engineering" | "compact";
export type RoundingPriorityType = "auto" | "morePrecision" | "lessPrecision";
export type NumberFormatRoundingType = "morePrecision" | "lessPrecision" | "significantDigits" | "fractionDigits";
export type RoundingModeType = "ceil" | "floor" | "expand" | "trunc" | "halfCeil" | "halfFloor" | "halfExpand" | "halfTrunc" | "halfEven";
export type UnsignedRoundingModeType = "infinity" | "zero" | "half-infinity" | "half-zero" | "half-even";
export type UseGroupingType = "min2" | "auto" | "always" | boolean;
export interface NumberFormatDigitOptions {
minimumIntegerDigits?: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
minimumFractionDigits?: number;
maximumFractionDigits?: number;
roundingPriority?: RoundingPriorityType;
roundingIncrement?: number;
roundingMode?: RoundingModeType;
trailingZeroDisplay?: TrailingZeroDisplay;
minimumIntegerDigits?: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
minimumFractionDigits?: number;
maximumFractionDigits?: number;
roundingPriority?: RoundingPriorityType;
roundingIncrement?: number;
roundingMode?: RoundingModeType;
trailingZeroDisplay?: TrailingZeroDisplay;
}
export interface NumberFormatDigitInternalSlots {
minimumIntegerDigits: number;
minimumSignificantDigits: number;
maximumSignificantDigits: number;
roundingType: NumberFormatRoundingType;
minimumFractionDigits: number;
maximumFractionDigits: number;
notation: NumberFormatNotation;
roundingIncrement: number;
roundingMode: RoundingModeType;
trailingZeroDisplay: TrailingZeroDisplay;
roundingPriority: RoundingPriorityType;
minimumIntegerDigits: number;
minimumSignificantDigits: number;
maximumSignificantDigits: number;
roundingType: NumberFormatRoundingType;
// These two properties are only used when `roundingType` is "fractionDigits".
minimumFractionDigits: number;
maximumFractionDigits: number;
notation: NumberFormatNotation;
roundingIncrement: number;
roundingMode: RoundingModeType;
trailingZeroDisplay: TrailingZeroDisplay;
roundingPriority: RoundingPriorityType;
}
// All fields are optional due to de-duping
export type RawNumberLocaleData = LocaleData<NumberFormatLocaleInternalData>;
export interface NumberFormatLocaleInternalData {
units: UnitDataTable;
currencies: Record<string, CurrencyData>;
numbers: RawNumberData;
nu: string[];
units: UnitDataTable;
currencies: Record<string, CurrencyData>;
numbers: RawNumberData;
// Bc of relevantExtensionKeys in the spec
nu: string[];
}
export interface UnitDataTable {
simple: Record<string, UnitData>;
compound: Record<string, CompoundUnitData>;
simple: Record<string, UnitData>;
compound: Record<string, CompoundUnitData>;
}
export interface UnitData {
long: LDMLPluralRuleMap<string>;
short: LDMLPluralRuleMap<string>;
narrow: LDMLPluralRuleMap<string>;
perUnit: Record<'narrow' | 'short' | 'long', string | undefined>;
// A pattern where {0} is number placeholder. Example: "摂氏 {0} 度".
long: LDMLPluralRuleMap<string>;
short: LDMLPluralRuleMap<string>;
narrow: LDMLPluralRuleMap<string>;
// perUnitPattern. See http://unicode.org/reports/tr35/tr35-general.html#perUnitPatterns
perUnit: Record<"narrow" | "short" | "long", string | undefined>;
}
// The values are patterns on how to compose simple units.
// For example, "{0} per {1}".
export interface CompoundUnitData {
long: string;
short: string;
narrow: string;
long: string;
short: string;
narrow: string;
}
export interface CurrencyData {
displayName: LDMLPluralRuleMap<string>;
symbol: string;
narrow: string;
displayName: LDMLPluralRuleMap<string>;
symbol: string;
narrow: string;
}
export type DecimalFormatNum = '1000' | '10000' | '100000' | '1000000' | '10000000' | '100000000' | '1000000000' | '10000000000' | '100000000000' | '1000000000000' | '10000000000000' | '100000000000000';
export type DecimalFormatNum = "1000" | "10000" | "100000" | "1000000" | "10000000" | "100000000" | "1000000000" | "10000000000" | "100000000000" | "1000000000000" | "10000000000000" | "100000000000000";
export type NumberingSystem = string;
/**
* We only care about insertBetween bc we assume
* `currencyMatch` & `surroundingMatch` are all the same
*
* @export
* @interface CurrencySpacingData
*/
* We only care about insertBetween bc we assume
* `currencyMatch` & `surroundingMatch` are all the same
*
* @export
* @interface CurrencySpacingData
*/
export interface CurrencySpacingData {
beforeInsertBetween: string;
afterInsertBetween: string;
beforeInsertBetween: string;
afterInsertBetween: string;
}
export interface RawCurrencyData {
currencySpacing: CurrencySpacingData;
standard: string;
accounting: string;
short?: Record<DecimalFormatNum, LDMLPluralRuleMap<string>>;
unitPattern: string;
currencySpacing: CurrencySpacingData;
standard: string;
accounting: string;
short?: Record<DecimalFormatNum, LDMLPluralRuleMap<string>>;
// IMPORTANT: We're making the assumption here that currency unitPattern
// are the same for all LDMLPluralRule
unitPattern: string;
}
export interface SymbolsData {
decimal: string;
group: string;
list: string;
percentSign: string;
plusSign: string;
minusSign: string;
exponential: string;
superscriptingExponent: string;
perMille: string;
infinity: string;
nan: string;
timeSeparator: string;
approximatelySign: string;
rangeSign: string;
currencyGroup?: string;
currencyDecimal?: string;
decimal: string;
group: string;
list: string;
percentSign: string;
plusSign: string;
minusSign: string;
exponential: string;
superscriptingExponent: string;
perMille: string;
infinity: string;
nan: string;
timeSeparator: string;
approximatelySign: string;
rangeSign: string;
currencyGroup?: string;
currencyDecimal?: string;
}
export interface RawNumberData {
nu: string[];
symbols: Record<NumberingSystem, SymbolsData>;
decimal: Record<NumberingSystem, {
standard: string;
long: Record<DecimalFormatNum, LDMLPluralRuleMap<string>>;
short: Record<DecimalFormatNum, LDMLPluralRuleMap<string>>;
}>;
percent: Record<NumberingSystem, string>;
currency: Record<NumberingSystem, RawCurrencyData>;
nu: string[];
// numberingSystem -> pattern
symbols: Record<NumberingSystem, SymbolsData>;
// numberingSystem -> pattern
decimal: Record<NumberingSystem, {
// The standard number pattern of the decimal.
standard: string;
// These two are compact notation mappings.
long: Record<DecimalFormatNum, LDMLPluralRuleMap<string>>;
short: Record<DecimalFormatNum, LDMLPluralRuleMap<string>>;
}>;
percent: Record<NumberingSystem, string>;
currency: Record<NumberingSystem, RawCurrencyData>;
}
export type LDMLPluralRuleMap<T> = Omit<Partial<Record<LDMLPluralRule, T>>, 'other'> & {
other: T;
export type LDMLPluralRuleMap<T> = Omit<Partial<Record<LDMLPluralRule, T>>, "other"> & {
other: T;
};
export interface RawNumberFormatResult {
formattedString: string;
roundedNumber: Decimal;
integerDigitsCount: number;
roundingMagnitude: number;
formattedString: string;
roundedNumber: Decimal;
integerDigitsCount: number;
roundingMagnitude: number;
}
export type NumberFormatOptionsLocaleMatcher = 'lookup' | 'best fit';
export type NumberFormatOptionsStyle = 'decimal' | 'percent' | 'currency' | 'unit';
export type NumberFormatOptionsCompactDisplay = 'short' | 'long';
export type NumberFormatOptionsCurrencyDisplay = 'symbol' | 'code' | 'name' | 'narrowSymbol';
export type NumberFormatOptionsCurrencySign = 'standard' | 'accounting';
export type NumberFormatOptionsLocaleMatcher = "lookup" | "best fit";
export type NumberFormatOptionsStyle = "decimal" | "percent" | "currency" | "unit";
export type NumberFormatOptionsCompactDisplay = "short" | "long";
export type NumberFormatOptionsCurrencyDisplay = "symbol" | "code" | "name" | "narrowSymbol";
export type NumberFormatOptionsCurrencySign = "standard" | "accounting";
export type NumberFormatOptionsNotation = NumberFormatNotation;
export type NumberFormatOptionsSignDisplay = 'auto' | 'always' | 'never' | 'exceptZero' | 'negative';
export type NumberFormatOptionsUnitDisplay = 'long' | 'short' | 'narrow';
export type TrailingZeroDisplay = 'auto' | 'stripIfInteger';
export type NumberFormatOptionsSignDisplay = "auto" | "always" | "never" | "exceptZero" | "negative";
export type NumberFormatOptionsUnitDisplay = "long" | "short" | "narrow";
export type TrailingZeroDisplay = "auto" | "stripIfInteger";
export interface NumberFormatInternal extends NumberFormatDigitInternalSlots {
locale: string;
dataLocale: string;
style: NumberFormatOptionsStyle;
currency?: string;
currencyDisplay: NumberFormatOptionsCurrencyDisplay;
unit?: string;
unitDisplay: NumberFormatOptionsUnitDisplay;
currencySign: NumberFormatOptionsCurrencySign;
notation: NumberFormatOptionsNotation;
compactDisplay: NumberFormatOptionsCompactDisplay;
signDisplay: NumberFormatOptionsSignDisplay;
useGrouping?: UseGroupingType;
pl: Intl.PluralRules;
boundFormat?: Intl.NumberFormat['format'];
numberingSystem: string;
dataLocaleData: NumberFormatLocaleInternalData;
roundingMode: RoundingModeType;
locale: string;
dataLocale: string;
style: NumberFormatOptionsStyle;
currency?: string;
currencyDisplay: NumberFormatOptionsCurrencyDisplay;
unit?: string;
unitDisplay: NumberFormatOptionsUnitDisplay;
currencySign: NumberFormatOptionsCurrencySign;
notation: NumberFormatOptionsNotation;
compactDisplay: NumberFormatOptionsCompactDisplay;
signDisplay: NumberFormatOptionsSignDisplay;
useGrouping?: UseGroupingType;
pl: Intl.PluralRules;
boundFormat?: Intl.NumberFormat["format"];
numberingSystem: string;
// Locale-dependent formatter data
dataLocaleData: NumberFormatLocaleInternalData;
roundingMode: RoundingModeType;
}
export type NumberFormatOptions = Omit<Intl.NumberFormatOptions, 'signDisplay' | 'useGrouping'> & NumberFormatDigitOptions & {
localeMatcher?: NumberFormatOptionsLocaleMatcher;
style?: NumberFormatOptionsStyle;
compactDisplay?: NumberFormatOptionsCompactDisplay;
currencyDisplay?: NumberFormatOptionsCurrencyDisplay;
currencySign?: NumberFormatOptionsCurrencySign;
notation?: NumberFormatOptionsNotation;
signDisplay?: NumberFormatOptionsSignDisplay;
unit?: string;
unitDisplay?: NumberFormatOptionsUnitDisplay;
numberingSystem?: string;
trailingZeroDisplay?: TrailingZeroDisplay;
roundingPriority?: RoundingPriorityType;
roundingIncrement?: number;
roundingMode?: RoundingModeType;
useGrouping?: UseGroupingType;
export type NumberFormatOptions = Omit<Intl.NumberFormatOptions, "signDisplay" | "useGrouping"> & NumberFormatDigitOptions & {
localeMatcher?: NumberFormatOptionsLocaleMatcher;
style?: NumberFormatOptionsStyle;
compactDisplay?: NumberFormatOptionsCompactDisplay;
currencyDisplay?: NumberFormatOptionsCurrencyDisplay;
currencySign?: NumberFormatOptionsCurrencySign;
notation?: NumberFormatOptionsNotation;
signDisplay?: NumberFormatOptionsSignDisplay;
unit?: string;
unitDisplay?: NumberFormatOptionsUnitDisplay;
numberingSystem?: string;
trailingZeroDisplay?: TrailingZeroDisplay;
roundingPriority?: RoundingPriorityType;
roundingIncrement?: number;
roundingMode?: RoundingModeType;
useGrouping?: UseGroupingType;
};
export type ResolvedNumberFormatOptions = Intl.ResolvedNumberFormatOptions & Pick<NumberFormatInternal, 'currencySign' | 'unit' | 'unitDisplay' | 'notation' | 'compactDisplay' | 'signDisplay'>;
export type NumberFormatPartTypes = Intl.NumberFormatPartTypes | 'exponentSeparator' | 'exponentMinusSign' | 'exponentInteger' | 'compact' | 'unit' | 'literal' | 'approximatelySign';
export type ResolvedNumberFormatOptions = Intl.ResolvedNumberFormatOptions & Pick<NumberFormatInternal, "currencySign" | "unit" | "unitDisplay" | "notation" | "compactDisplay" | "signDisplay">;
export type NumberFormatPartTypes = Intl.NumberFormatPartTypes | "exponentSeparator" | "exponentMinusSign" | "exponentInteger" | "compact" | "unit" | "literal" | "approximatelySign";
export interface NumberFormatPart {
type: NumberFormatPartTypes;
value: string;
source?: string;
type: NumberFormatPartTypes;
value: string;
source?: string;
}
export interface NumberRangeToParts extends NumberFormatPart {
result: string;
result: string;
}

@@ -1,1 +0,2 @@

export {};
import "./core.js";
import "./plural-rules.js";

@@ -1,16 +0,16 @@

import { LocaleData } from './core.js';
import { NumberFormatDigitInternalSlots } from './number.js';
export type LDMLPluralRule = 'zero' | 'one' | 'two' | 'few' | 'many' | 'other';
import { type LocaleData } from "./core.js";
import { type NumberFormatDigitInternalSlots } from "./number.js";
export type LDMLPluralRule = "zero" | "one" | "two" | "few" | "many" | "other";
export interface PluralRulesData {
categories: {
cardinal: string[];
ordinal: string[];
};
fn: (val: number | string, ord?: boolean) => LDMLPluralRule;
categories: {
cardinal: string[];
ordinal: string[];
};
fn: (val: number | string, ord?: boolean) => LDMLPluralRule;
}
export type PluralRulesLocaleData = LocaleData<PluralRulesData>;
export interface PluralRulesInternal extends NumberFormatDigitInternalSlots {
initializedPluralRules: boolean;
locale: string;
type: 'cardinal' | 'ordinal';
initializedPluralRules: boolean;
locale: string;
type: "cardinal" | "ordinal";
}

@@ -1,1 +0,2 @@

export {};
import "./core.js";
import "./number.js";

@@ -1,40 +0,34 @@

import { LocaleData } from './core.js';
import { LDMLPluralRule } from './plural-rules.js';
import { type LocaleData } from "./core.js";
import { type LDMLPluralRule } from "./plural-rules.js";
export interface FieldData {
'0'?: string;
'1'?: string;
'-1'?: string;
'2'?: string;
'-2'?: string;
'3'?: string;
'-3'?: string;
future: RelativeTimeData;
past: RelativeTimeData;
"0"?: string;
"1"?: string;
"-1"?: string;
"2"?: string;
"-2"?: string;
"3"?: string;
"-3"?: string;
future: RelativeTimeData;
past: RelativeTimeData;
}
type RelativeTimeData = {
[u in LDMLPluralRule]?: string;
type RelativeTimeData = { [u in LDMLPluralRule]? : string };
export type UnpackedLocaleFieldsData = { [f in RelativeTimeField]? : FieldData } & {
nu: Array<string | null>;
};
export type UnpackedLocaleFieldsData = {
[f in RelativeTimeField]?: FieldData;
} & {
nu: Array<string | null>;
export type LocaleFieldsData = { [f in RelativeTimeField]? : FieldData } & {
nu?: Array<string | null>;
};
export type LocaleFieldsData = {
[f in RelativeTimeField]?: FieldData;
} & {
nu?: Array<string | null>;
};
export type RelativeTimeField = 'second' | 'second-short' | 'second-narrow' | 'minute' | 'minute-short' | 'minute-narrow' | 'hour' | 'hour-short' | 'hour-narrow' | 'day' | 'day-short' | 'day-narrow' | 'week' | 'week-short' | 'week-narrow' | 'month' | 'month-short' | 'month-narrow' | 'quarter' | 'quarter-short' | 'quarter-narrow' | 'year' | 'year-short' | 'year-narrow';
export type RelativeTimeFormatSingularUnit = Exclude<Intl.RelativeTimeFormatUnit, 'seconds' | 'minutes' | 'hours' | 'days' | 'weeks' | 'months' | 'quarters' | 'years'>;
export type RelativeTimeField = "second" | "second-short" | "second-narrow" | "minute" | "minute-short" | "minute-narrow" | "hour" | "hour-short" | "hour-narrow" | "day" | "day-short" | "day-narrow" | "week" | "week-short" | "week-narrow" | "month" | "month-short" | "month-narrow" | "quarter" | "quarter-short" | "quarter-narrow" | "year" | "year-short" | "year-narrow";
export type RelativeTimeFormatSingularUnit = Exclude<Intl.RelativeTimeFormatUnit, "seconds" | "minutes" | "hours" | "days" | "weeks" | "months" | "quarters" | "years">;
export type RelativeTimeLocaleData = LocaleData<LocaleFieldsData>;
export interface RelativeTimeFormatInternal {
numberFormat: Intl.NumberFormat;
pluralRules: Intl.PluralRules;
locale: string;
fields: LocaleFieldsData;
style: Intl.ResolvedRelativeTimeFormatOptions['style'];
numeric: Intl.ResolvedRelativeTimeFormatOptions['numeric'];
numberingSystem: string;
initializedRelativeTimeFormat: boolean;
numberFormat: Intl.NumberFormat;
pluralRules: Intl.PluralRules;
locale: string;
fields: LocaleFieldsData;
style: Intl.ResolvedRelativeTimeFormatOptions["style"];
numeric: Intl.ResolvedRelativeTimeFormatOptions["numeric"];
numberingSystem: string;
initializedRelativeTimeFormat: boolean;
}
export {};

@@ -1,1 +0,2 @@

export {};
import "./core.js";
import "./plural-rules.js";
export declare function repeat(s: string, times: number): string;
export declare function setInternalSlot<Instance extends object, Internal extends object, Field extends keyof Internal>(map: WeakMap<Instance, Internal>, pl: Instance, field: Field, value: NonNullable<Internal>[Field]): void;
export declare function setMultiInternalSlots<Instance extends object, Internal extends object, K extends keyof Internal>(map: WeakMap<Instance, Internal>, pl: Instance, props: Pick<NonNullable<Internal>, K>): void;
export declare function getInternalSlot<Instance extends object, Internal extends object, Field extends keyof Internal>(map: WeakMap<Instance, Internal>, pl: Instance, field: Field): Internal[Field];
export declare function getMultiInternalSlots<Instance extends object, Internal extends object, Field extends keyof Internal>(map: WeakMap<Instance, Internal>, pl: Instance, ...fields: Field[]): Pick<Internal, Field>;
export declare function setInternalSlot<
Instance extends object,
Internal extends object,
Field extends keyof Internal
>(map: WeakMap<Instance, Internal>, pl: Instance, field: Field, value: NonNullable<Internal>[Field]): void;
export declare function setMultiInternalSlots<
Instance extends object,
Internal extends object,
K extends keyof Internal
>(map: WeakMap<Instance, Internal>, pl: Instance, props: Pick<NonNullable<Internal>, K>): void;
export declare function getInternalSlot<
Instance extends object,
Internal extends object,
Field extends keyof Internal
>(map: WeakMap<Instance, Internal>, pl: Instance, field: Field): Internal[Field];
export declare function getMultiInternalSlots<
Instance extends object,
Internal extends object,
Field extends keyof Internal
>(map: WeakMap<Instance, Internal>, pl: Instance, ...fields: Field[]): Pick<Internal, Field>;
export interface LiteralPart {
type: 'literal';
value: string;
type: "literal";
value: string;
}
export declare function isLiteralPart(patternPart: LiteralPart | {
type: string;
value?: string;
type: string;
value?: string;
}): patternPart is LiteralPart;
/*
17 ECMAScript Standard Built-in Objects:
Every built-in Function object, including constructors, that is not
identified as an anonymous function has a name property whose value
is a String.
Unless otherwise specified, the name property of a built-in Function
object, if it exists, has the attributes { [[Writable]]: false,
[[Enumerable]]: false, [[Configurable]]: true }.
*/
export declare function defineProperty<T extends object>(target: T, name: string | symbol, { value }: {
value: any;
value: any;
} & ThisType<any>): void;
/**
* 7.3.5 CreateDataProperty
* @param target
* @param name
* @param value
*/
* 7.3.5 CreateDataProperty
* @param target
* @param name
* @param value
*/
export declare function createDataProperty<T extends object>(target: T, name: string | symbol, value: any): void;

@@ -24,0 +50,0 @@ export declare const UNICODE_EXTENSION_SEQUENCE_REGEX: RegExp;

+63
-116

@@ -1,135 +0,82 @@

import { __spreadArray } from "tslib";
import { memoize, strategies } from '@formatjs/fast-memoize';
import { memoize, strategies } from "@formatjs/fast-memoize";
export function repeat(s, times) {
if (typeof s.repeat === 'function') {
return s.repeat(times);
}
var arr = Array.from({ length: times });
for (var i = 0; i < arr.length; i++) {
arr[i] = s;
}
return arr.join('');
if (typeof s.repeat === "function") {
return s.repeat(times);
}
const arr = Array.from({ length: times });
for (let i = 0; i < arr.length; i++) {
arr[i] = s;
}
return arr.join("");
}
export function setInternalSlot(map, pl, field, value) {
if (!map.get(pl)) {
map.set(pl, Object.create(null));
}
var slots = map.get(pl);
slots[field] = value;
if (!map.get(pl)) {
map.set(pl, Object.create(null));
}
const slots = map.get(pl);
slots[field] = value;
}
export function setMultiInternalSlots(map, pl, props) {
for (var _i = 0, _a = Object.keys(props); _i < _a.length; _i++) {
var k = _a[_i];
setInternalSlot(map, pl, k, props[k]);
}
for (const k of Object.keys(props)) {
setInternalSlot(map, pl, k, props[k]);
}
}
export function getInternalSlot(map, pl, field) {
return getMultiInternalSlots(map, pl, field)[field];
return getMultiInternalSlots(map, pl, field)[field];
}
export function getMultiInternalSlots(map, pl) {
var fields = [];
for (var _i = 2; _i < arguments.length; _i++) {
fields[_i - 2] = arguments[_i];
}
var slots = map.get(pl);
if (!slots) {
throw new TypeError("".concat(pl, " InternalSlot has not been initialized"));
}
return fields.reduce(function (all, f) {
all[f] = slots[f];
return all;
}, Object.create(null));
export function getMultiInternalSlots(map, pl, ...fields) {
const slots = map.get(pl);
if (!slots) {
throw new TypeError(`${pl} InternalSlot has not been initialized`);
}
return fields.reduce((all, f) => {
all[f] = slots[f];
return all;
}, Object.create(null));
}
export function isLiteralPart(patternPart) {
return patternPart.type === 'literal';
return patternPart.type === "literal";
}
/*
17 ECMAScript Standard Built-in Objects:
Every built-in Function object, including constructors, that is not
identified as an anonymous function has a name property whose value
is a String.
17 ECMAScript Standard Built-in Objects:
Every built-in Function object, including constructors, that is not
identified as an anonymous function has a name property whose value
is a String.
Unless otherwise specified, the name property of a built-in Function
object, if it exists, has the attributes { [[Writable]]: false,
[[Enumerable]]: false, [[Configurable]]: true }.
Unless otherwise specified, the name property of a built-in Function
object, if it exists, has the attributes { [[Writable]]: false,
[[Enumerable]]: false, [[Configurable]]: true }.
*/
export function defineProperty(target, name, _a) {
var value = _a.value;
Object.defineProperty(target, name, {
configurable: true,
enumerable: false,
writable: true,
value: value,
});
export function defineProperty(target, name, { value }) {
Object.defineProperty(target, name, {
configurable: true,
enumerable: false,
writable: true,
value
});
}
/**
* 7.3.5 CreateDataProperty
* @param target
* @param name
* @param value
*/
* 7.3.5 CreateDataProperty
* @param target
* @param name
* @param value
*/
export function createDataProperty(target, name, value) {
Object.defineProperty(target, name, {
configurable: true,
enumerable: true,
writable: true,
value: value,
});
Object.defineProperty(target, name, {
configurable: true,
enumerable: true,
writable: true,
value
});
}
export var UNICODE_EXTENSION_SEQUENCE_REGEX = /-u(?:-[0-9a-z]{2,8})+/gi;
export function invariant(condition, message, Err) {
if (Err === void 0) { Err = Error; }
if (!condition) {
throw new Err(message);
}
export const UNICODE_EXTENSION_SEQUENCE_REGEX = /-u(?:-[0-9a-z]{2,8})+/gi;
export function invariant(condition, message, Err = Error) {
if (!condition) {
throw new Err(message);
}
}
export var createMemoizedNumberFormat = memoize(function () {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return new ((_a = Intl.NumberFormat).bind.apply(_a, __spreadArray([void 0], args, false)))();
}, {
strategy: strategies.variadic,
});
export var createMemoizedDateTimeFormat = memoize(function () {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return new ((_a = Intl.DateTimeFormat).bind.apply(_a, __spreadArray([void 0], args, false)))();
}, {
strategy: strategies.variadic,
});
export var createMemoizedPluralRules = memoize(function () {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return new ((_a = Intl.PluralRules).bind.apply(_a, __spreadArray([void 0], args, false)))();
}, {
strategy: strategies.variadic,
});
export var createMemoizedLocale = memoize(function () {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return new ((_a = Intl.Locale).bind.apply(_a, __spreadArray([void 0], args, false)))();
}, {
strategy: strategies.variadic,
});
export var createMemoizedListFormat = memoize(function () {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return new ((_a = Intl.ListFormat).bind.apply(_a, __spreadArray([void 0], args, false)))();
}, {
strategy: strategies.variadic,
});
export const createMemoizedNumberFormat = memoize((...args) => new Intl.NumberFormat(...args), { strategy: strategies.variadic });
export const createMemoizedDateTimeFormat = memoize((...args) => new Intl.DateTimeFormat(...args), { strategy: strategies.variadic });
export const createMemoizedPluralRules = memoize((...args) => new Intl.PluralRules(...args), { strategy: strategies.variadic });
export const createMemoizedLocale = memoize((...args) => new Intl.Locale(...args), { strategy: strategies.variadic });
export const createMemoizedListFormat = memoize((...args) => new Intl.ListFormat(...args), { strategy: strategies.variadic });