builtin_bigint.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package goja
  2. func (r *Runtime) bigintproto_valueOf(call FunctionCall) Value {
  3. this := call.This
  4. if !isBigInt(this) {
  5. r.typeErrorResult(true, "Value is not a bigint")
  6. }
  7. switch t := this.(type) {
  8. case valueBigInt:
  9. return this
  10. case *Object:
  11. if v, ok := t.self.(*primitiveValueObject); ok {
  12. return v.pValue
  13. }
  14. }
  15. panic(r.NewTypeError("BigInt.prototype.valueOf is not generic"))
  16. }
  17. func isBigInt(v Value) bool {
  18. switch t := v.(type) {
  19. case valueBigInt:
  20. return true
  21. case *Object:
  22. switch t := t.self.(type) {
  23. case *primitiveValueObject:
  24. return isBigInt(t.pValue)
  25. }
  26. }
  27. return false
  28. }
  29. func (r *Runtime) bigintproto_toString(call FunctionCall) Value {
  30. this := call.This
  31. if !isBigInt(this) {
  32. r.typeErrorResult(true, "Value is not a bigint")
  33. }
  34. b := call.This.ToBigInt()
  35. if t, ok := b.(valueBigInt); ok {
  36. return asciiString(t.Int.String())
  37. }
  38. panic(r.NewTypeError("BigInt.prototype.toString is not generic"))
  39. }
  40. func (r *Runtime) initBigInt() {
  41. r.global.BigIntPrototype = r.newPrimitiveObject(valueInt(0), r.global.ObjectPrototype, classBigInt)
  42. o := r.global.BigIntPrototype.self
  43. o._putProp("toString", r.newNativeFunc(r.bigintproto_toString, nil, "toString", nil, 1), true, false, true)
  44. o._putProp("valueOf", r.newNativeFunc(r.bigintproto_valueOf, nil, "valueOf", nil, 0), true, false, true)
  45. r.global.BigInt = r.newNativeFunc(r.builtin_BigInt, r.builtin_newBigInt, "BigInt", r.global.BigIntPrototype, 1)
  46. r.addToGlobal("BigInt", r.global.BigInt)
  47. }