• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16/*
17 * @tc.name:arraywith
18 * @tc.desc:test Array.with
19 * @tc.type: FUNC
20 * @tc.require: issueI5NO8G
21 */
22
23const arr0 = [0, , undefined, 1];
24print(arr0.indexOf(undefined));
25const arr1 = arr0.with(0, 0);
26print(arr0.indexOf(undefined));
27print(arr1.indexOf(undefined));
28
29const arr2 = new Array(1025);
30for(let i = 0; i < 1025; i = i + 1)
31    arr2[i] = i;
32const arr3 = arr2.with(0, 0);
33
34var arr4 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
35var arr5 = new Array();
36for (let i = 0; i < 10; i++) arr5[i] = i;
37
38var result1 = arr4.with(4, 100);
39print(result1);
40var result2 = arr5.with(4, 100);
41print(result2);
42
43let outputs = []
44// testCase1: use only one parameter in Array.prototype.with()
45const caseOneArr1 = [0, 1, 2, 3, 4, 5, , 7, 8, undefined];
46outputs.push(caseOneArr1.indexOf(undefined));
47const caseOneArr2 = caseOneArr1.with(2);
48outputs.push(caseOneArr2.indexOf(undefined));
49
50// testCase2: mixed-type array
51const caseTwoArray1 = [1, "two", 3, "four"];
52const caseTwoArray2 = caseTwoArray1.with(2, "three");
53outputs.push(caseTwoArray2);
54
55// testCase3: replace undefined or null
56const caseThreeArray1 = [undefined, null, 3, 4];
57const caseThreeArray2 = caseThreeArray1.with(0, 1);
58const caseThreeArray3 = caseThreeArray1.with(1, "two");
59outputs.push(caseThreeArray2);
60outputs.push(caseThreeArray3);
61
62// testCase4: replace by boolean, object or function
63const caseFourArray1 = [1, "two", 3, "four"];
64const caseFourArray2 = caseFourArray1.with(0, false);
65const caseFourArray3 = caseFourArray1.with(1, { key: "value" });
66const caseFourArray4 = caseFourArray1.with(2, () => "world");
67outputs.push(caseFourArray2);
68outputs.push(caseFourArray3);
69outputs.push(caseFourArray4);
70
71// testCase5: deal with sparse array
72const caseFiveArray1 = [1, , 3, , 5];
73const caseFiveArray2 = caseFiveArray1.with(1, "two");
74outputs.push(caseFiveArray2);
75
76// testCase6: deal with indices that are negative or out of bounds
77const caseSixArray1 = [1, 2, 3, 4];
78const caseSixArray2 = caseSixArray1.with(-1, 2);
79outputs.push(caseSixArray2);
80try {
81    print(caseSixArray1.with(-6, 2));
82} catch (error) {
83    print(error);
84}
85
86print(outputs.map(out => JSON.stringify(out)).join('\n'));
87