Skip to content

Commit 5feb355

Browse files
committed
Optimization of code
1 parent 3538a6a commit 5feb355

1 file changed

Lines changed: 6 additions & 13 deletions

File tree

RandSum0/index.js

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,32 +9,25 @@ class genSum{
99
this.array.length = 0;
1010

1111
for(let i = 0; i < n; i++){
12-
let num = this.pickRandNum({
13-
min: 0,
14-
max: 100,
15-
negative: true});
16-
while(this.array.includes(num)) {
12+
let num;
13+
do {
1714
num = this.pickRandNum({
1815
min: 0,
1916
max: 100,
20-
negative: true}) // between min/max/max in negative
21-
}
17+
negative: true});
18+
}while(this.array.includes(num))
2219
this.array.push(num);
2320
}
2421
arrSum = this.sumArray();
2522
}
2623
}
2724
pickRandNum({min,max,negative = false}){
2825
let num = Math.floor(Math.random()* max) + min;
29-
if(negative) num *= Math.floor(Math.random()*2) == 1 ? 1 : -1;
26+
if(negative) num *= Math.random() > 0.5 ? 1 : -1;
3027
return num;
3128
}
3229
sumArray(){
33-
let sum = 0;
34-
for(let i = 0; i < this.array.length; i++){
35-
sum += this.array[i];
36-
}
37-
return sum;
30+
return this.array.reduce((a,b)=>a+b);
3831
}
3932
}
4033

0 commit comments

Comments
 (0)