-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2695-ArrayWrapper.js
More file actions
81 lines (71 loc) · 2.11 KB
/
2695-ArrayWrapper.js
File metadata and controls
81 lines (71 loc) · 2.11 KB
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
// 2695. Array Wrapper
// Create a class ArrayWrapper that accepts an array of integers in its constructor.
// This class should have two features:
// When two instances of this class are added together with the + operator, the resulting value is the sum of all the elements in both arrays.
// When the String() function is called on the instance, it will return a comma separated string surrounded by brackets. For example, [1,2,3].
// Example 1:
// Input: nums = [[1,2],[3,4]], operation = "Add"
// Output: 10
// Explanation:
// const obj1 = new ArrayWrapper([1,2]);
// const obj2 = new ArrayWrapper([3,4]);
// obj1 + obj2; // 10
// Example 2:
// Input: nums = [[23,98,42,70]], operation = "String"
// Output: "[23,98,42,70]"
// Explanation:
// const obj = new ArrayWrapper([23,98,42,70]);
// String(obj); // "[23,98,42,70]"
// Example 3:
// Input: nums = [[],[]], operation = "Add"
// Output: 0
// Explanation:
// const obj1 = new ArrayWrapper([]);
// const obj2 = new ArrayWrapper([]);
// obj1 + obj2; // 0
// Constraints:
// 0 <= nums.length <= 1000
// 0 <= nums[i] <= 1000
// Note: nums is the array passed to the constructor
/**
* @param {number[]} nums
* @return {void}
*/
var ArrayWrapper = function(nums) {
this.data = nums;
};
/**
* @return {number}
*/
ArrayWrapper.prototype.valueOf = function() {
// let res = 0;
// // 累加起来返回
// for(let i in this.data) {
// res += this.data[i];
// }
// return res;
return this.data.reduce((a, b) => a + b, 0);
}
/**
* @return {string}
*/
ArrayWrapper.prototype.toString = function() {
// let res = [];
// for(let i in this.data) {
// res.push(this.data[i]);
// }
// return "[" + res.join(",") + "]";
return JSON.stringify(this.data);
}
/**
* const obj1 = new ArrayWrapper([1,2]);
* const obj2 = new ArrayWrapper([3,4]);
* obj1 + obj2; // 10
* String(obj1); // "[1,2]"
* String(obj2); // "[3,4]"
*/
const obj1 = new ArrayWrapper([1,2]);
const obj2 = new ArrayWrapper([3,4]);
console.log(obj1 + obj2); // 10
console.log(String(obj1)); // "[1,2]"
console.log(String(obj2)); // "[3,4]"