-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path5-3.js
39 lines (34 loc) · 810 Bytes
/
5-3.js
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
class SparseArray {
constructor() {
this.hash = {};
}
init(arr=[]) {
for(let i = 0; i < arr.length; i++){
if (arr[i] !== 0) {
this.hash[i] = arr[i];
}
}
}
set(i, val){
if (i !== 0) {
this.hash[i] = val;
} else {
delete this.hash[i];
}
}
get(i){
return this.hash[i] ? this.hash[i] : 0;
}
toString() {
Object.keys(this.hash).forEach(key => {
var value = this.hash[key];
console.log(`${key}: ${value}`);
});
console.log('\n');
}
}
let sparseArray = new SparseArray();
sparseArray.init([0,1,0,0,2,0,0,0,3,0,0,0,0,4,0,0,0,0,0,5]);
sparseArray.toString();
sparseArray.set(21, 6);
sparseArray.toString();