summaryrefslogtreecommitdiff
path: root/deps/v8/test/mjsunit/harmony/array-flatMap.js
blob: d129c32e03c0d662466d22c1e3c2980de5af4459 (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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
// Copyright 2018 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: --harmony-array-flatten --allow-natives-syntax

assertEquals(Array.prototype.flatMap.length, 1);
assertEquals(Array.prototype.flatMap.name, 'flatMap');

assertEquals(
  [1, 2, 3, 4].flatMap((element) => [element, element ** 2]),
  [1, 1, 2, 4, 3, 9, 4, 16]
);
assertEquals(
  [1, 2, 3, 4].flatMap((element) => [[element, element ** 2]]),
  [[1, 1], [2, 4], [3, 9], [4, 16]]
);

const elements = new Set([
  -Infinity,
  -1,
  -0,
  +0,
  +1,
  Infinity,
  null,
  undefined,
  true,
  false,
  '',
  'foo',
  /./,
  [],
  {},
  Object.create(null),
  new Proxy({}, {}),
  Symbol(),
  x => x ** 2,
  String
]);

for (const value of elements) {
  assertEquals(
    [value].flatMap((element) => [element, element]),
    [value, value]
  );
}

const array = [42];
assertEquals(
  [array].flatMap((element) => [element, element]),
  [array, array]
);

const nonCallables = new Set([
  -Infinity,
  -1,
  -0,
  +0,
  +1,
  Infinity,
  null,
  undefined,
  true,
  false,
  '',
  'foo',
  /./,
  [],
  {},
  Object.create(null),
  new Proxy({}, {}),
  Symbol(),
]);
for (const nonCallable of nonCallables) {
  assertThrows(() => {
    [].flatMap(nonCallable);
  }, TypeError);
}

const object = {
  foo: 42,
  get length() {
    object.foo = 0;
  }
};
const result = [object].flatMap((element) => [element, element]);
%HeapObjectVerify(result);
assertEquals(result, [object, object]);
assertEquals(result[0].foo, 42);

assertThrows(() => {
  Array.prototype.flatMap.call(null, (element) => element);
}, TypeError);
assertThrows(() => {
  Array.prototype.flatMap.call(undefined, (element) => element);
}, TypeError);

assertEquals(
  Array.prototype.flatMap.call(
    {
      length: 1,
      0: 'a',
      1: 'b',
    },
    (element) => element
  ),
  ['a']
);
assertEquals(
  Array.prototype.flatMap.call(
    {
      length: 2,
      0: 'a',
      1: 'b',
    },
    (element) => element
  ),
  ['a', 'b']
);