summaryrefslogtreecommitdiff
path: root/deps/v8/test/mjsunit/harmony/bigint/json.js
blob: cf392234c5c960ce6382dc663b56baa890c151ad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Flags: --allow-natives-syntax

'use strict'


// Without .toJSON method.

assertEquals(undefined, BigInt.prototype.toJSON);
assertThrows(() => JSON.stringify(42n), TypeError);
assertThrows(() => JSON.stringify(Object(42n)), TypeError);


// With .toJSON method that returns a string.

BigInt.prototype.toJSON = function() {
  assertEquals("bigint", typeof this);
  return String(this);
}
assertEquals("\"42\"", JSON.stringify(42n));

BigInt.prototype.toJSON = function() {
  assertEquals("object", typeof this);
  return String(this);
}
assertEquals("\"42\"", JSON.stringify(Object(42n)));


// With .toJSON method that returns a BigInt primitive.

BigInt.prototype.toJSON = function() {return this};
assertThrows(() => JSON.stringify(42n), TypeError);
assertThrows(() => JSON.stringify(Object(42n)), TypeError);


// With .toJSON method that returns a BigInt object.

BigInt.prototype.toJSON = function() {return Object(this)};
assertThrows(() => JSON.stringify(42n), TypeError);
assertThrows(() => JSON.stringify(Object(42n)), TypeError);


// Without .toJSON method but with a replacer returning a string.

delete BigInt.prototype.toJSON;
let replacer;

replacer = function(k, v) {
  assertEquals("bigint", typeof v);
  assertTrue(42n == v);
  return "43";
}
assertEquals("\"43\"", JSON.stringify(42n, replacer));

replacer = function(k, v) {
  assertEquals("object", typeof v);
  assertTrue(42n == v);
  return "43";
}
assertEquals("\"43\"", JSON.stringify(Object(42n), replacer));


// Without .toJSON method but with a replacer returning a BigInt primitive.

assertEquals(undefined, BigInt.prototype.toJSON);

replacer = () => 43n;
assertThrows(() => JSON.stringify(42n, replacer), TypeError);
assertThrows(() => JSON.stringify(Object(42n), replacer), TypeError);


// Without .toJSON method but with a replacer returning a BigInt object.

assertEquals(undefined, BigInt.prototype.toJSON);

replacer = () => Object(43n);
assertThrows(() => JSON.stringify(42n, replacer), TypeError);
assertThrows(() => JSON.stringify(Object(42n), replacer), TypeError);