add number literal jsbigints.big (#17707)

This commit is contained in:
Timothee Cour
2021-04-13 00:33:28 -07:00
committed by GitHub
parent 4f5709e326
commit e92c78a9ac
2 changed files with 16 additions and 10 deletions

View File

@@ -13,16 +13,22 @@ func big*(integer: SomeInteger): JsBigInt {.importjs: "BigInt(#)".} =
doAssert 0b1111100111.big == 0o1747.big and 0o1747.big == 999.big
when nimvm: doAssert false, "JsBigInt can not be used at compile-time nor static context" else: discard
func big*(integer: cstring): JsBigInt {.importjs: "BigInt(#)".} =
func `'big`*(num: cstring): JsBigInt {.importjs: "BigInt(#)".} =
## Constructor for `JsBigInt`.
runnableExamples:
doAssert big"-1" == big"1" - big"2"
doAssert -1'big == 1'big - 2'big
# supports decimal, binary, octal, hex:
doAssert big"12" == 12.big
doAssert big"0b101" == 0b101.big
doAssert big"0o701" == 0o701.big
doAssert big"0xdeadbeaf" == 0xdeadbeaf.big
doAssert big"0xffffffffffffffff" == (1.big shl 64.big) - 1.big
doAssert -12'big == big"-12"
doAssert 12'big == 12.big
doAssert 0b101'big == 0b101.big
doAssert 0o701'big == 0o701.big
doAssert 0xdeadbeaf'big == 0xdeadbeaf.big
doAssert 0xffffffffffffffff'big == (1'big shl 64'big) - 1'big
doAssert not compiles(static(12'big))
when nimvm: doAssert false, "JsBigInt can not be used at compile-time nor static context" else: discard
func big*(integer: cstring): JsBigInt {.importjs: "BigInt(#)".} =
## Alias for `'big`
when nimvm: doAssert false, "JsBigInt can not be used at compile-time nor static context" else: discard
func toCstring*(this: JsBigInt; radix: 2..36): cstring {.importjs: "#.toString(#)".} =

View File

@@ -26,7 +26,7 @@ doAssert big1.toCstring(10) == "2147483647".cstring
doAssert big2 ** big3 == big(443556)
var huge = big"999999999999999999999999999999999999999999999999999999999999999999999999999999999999999"
huge.inc
huge = huge + big"-999999999999999999999999999999999999999999999999999999999999999999999999999999999999999"
huge = huge + -999999999999999999999999999999999999999999999999999999999999999999999999999999999999999'big
doAssert huge == big"1"
var list: seq[JsBigInt]
for i in big"0" .. big"5":
@@ -40,7 +40,7 @@ for i in big"0" ..< big"5":
doAssert list == @[big"0", big"1", big"2", big"3", big"4"]
block:
let b = big"2"
doAssert -b ** big"3" == big"-8"
let b = 2'big
doAssert -b ** 3'big == -8'big
doAssert -b ** big"2" == big"4" # not -4 because of precedence
doAssert -big"3" == big"-3"