From 301bba8c19f6b05ccbd1296e4420e914ac470986 Mon Sep 17 00:00:00 2001 From: davidot Date: Wed, 3 Aug 2022 21:33:02 +0200 Subject: [PATCH] LibJS: Only coerce value once in BigInt constructor See https://github.com/tc39/ecma262/pull/2812. --- .../Libraries/LibJS/Runtime/BigIntConstructor.cpp | 4 ++-- .../LibJS/Tests/builtins/BigInt/BigInt.js | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/Userland/Libraries/LibJS/Runtime/BigIntConstructor.cpp b/Userland/Libraries/LibJS/Runtime/BigIntConstructor.cpp index 739d40d313..98eae0460e 100644 --- a/Userland/Libraries/LibJS/Runtime/BigIntConstructor.cpp +++ b/Userland/Libraries/LibJS/Runtime/BigIntConstructor.cpp @@ -52,8 +52,8 @@ ThrowCompletionOr BigIntConstructor::call() if (primitive.is_number()) return TRY(number_to_bigint(global_object, primitive)); - // 4. Otherwise, return ? ToBigInt(value). - return TRY(value.to_bigint(global_object)); + // 4. Otherwise, return ? ToBigInt(prim). + return TRY(primitive.to_bigint(global_object)); } // 21.2.1.1 BigInt ( value ), https://tc39.es/ecma262/#sec-bigint-constructor-number-value diff --git a/Userland/Libraries/LibJS/Tests/builtins/BigInt/BigInt.js b/Userland/Libraries/LibJS/Tests/builtins/BigInt/BigInt.js index 33e1ff5ed5..7517ceffe4 100644 --- a/Userland/Libraries/LibJS/Tests/builtins/BigInt/BigInt.js +++ b/Userland/Libraries/LibJS/Tests/builtins/BigInt/BigInt.js @@ -63,6 +63,20 @@ describe("correct behavior", () => { expect(BigInt("0X10")).toBe(16n); expect(BigInt(`0x${"f".repeat(25)}`)).toBe(1267650600228229401496703205375n); }); + + test("only coerces value once", () => { + let calls = 0; + const value = { + [Symbol.toPrimitive]() { + expect(calls).toBe(0); + ++calls; + return "123"; + }, + }; + + expect(BigInt(value)).toEqual(123n); + expect(calls).toBe(1); + }); }); describe("errors", () => {