I have an interesting problem to solve and despite having a running solution, I was wondering where I could improve it.
In a range from 1 to 1000, I want to create an array with different increments according to the current interval. So, from 1.0 to 2.0, the increment should be 0.01, from 2.0 to 4.0 it should be 0.02, and so on. There are many intervals. The final result yields an array with 350 fields.
I've come up with a super basic, easy to implement solution using ifs. So it goes something like:
// In one file I have:
const grid = new Grid().buildGrid();
console.log(grid); // And expect a grid which respects the rules defined in the below class.
// Grid Class:
class Grid {
constructor() {
this.array = [];
}
buildGrid() {
_createKeysWithTicks(this.array);
}
_createKeysWithTicks(array){
let i = 1.0;
while (i < 1000){
i = parseFloat((i + findStepSize(i)).toFixed(2));
array.push(i);
}
return array;
}
findStepSize(number) {
let res;
if (number >= 1.0 && number < 2.0) {
res = 0.01;
} else if (number >= 2.0 && number < 4.0) {
res = 0.02;
} else if (number >= 4.0 && number < 5.0) {
res = 0.1;
} else if (number >= 5.0 && number < 10.0) {
res = 0.5;
} else if (number >= 10.0 && number < 50.0) {
res = 1.0;
} else if (number >= 50.0 && number < 100.0) {
res = 10;
}
return res;
}
However, this is not elegant, at all because I get numerous if statements. I could swap for a switch statement, thus reducing the number of comparisons, which is nice. But does it improve performance?
The suggestion is:
findStepSize(i) {
let res;
switch (number):
case(number >= 1.0 && number < 2.0) {
res = 0.01;
break;
case(number >= 2.0 && number < 4.0) {
res = 0.02;
break;
case(number >= 4.0 && number < 5.0) {
res = 0.1;
break;
case(number >= 5.0 && number < 10.0) {
res = 0.5;
break;
case(number >= 10.0 && number < 50.0) {
res = 1.0;
break;
case(number >= 50.0 && number < 100.0) {
res = 10;
break;
}
return res;
}
The increments are not linear, otherwise the solution could be different.
How would you optimize or clean this code?
Note: I understand and respect the rules of this community and I appreciate your feedback. Unfortunately, I cannot disclose much more details. If this is still not sufficient for you to think of how would you get rid of those If statements, I can't help much more because I can't simply provide more details. In fact, the data above is random and it's not the use case.