I am trying to see if I can reduce the code below with less JavaScript. When the user select Even dropdown option the only differences between that and the else statement is "i = 0" and "i % 2 === 0"
any recommendations? Maybe conditional operator would be best method? thank you
if (this.selection == "even") {
for (let i = 0; i <= number; i++) {
if (i % 2 === 0)
this.results.push(i + "\n");
}
} else {
for (let i = 1; i <= number; i++) {
if (i % 2 !== 0)
this.results.push(i + "\n");
}
}
Use this.selection to determine the starting number, then increment by 2 inside the loop instead of i++, so you don't have to check i % 2.
const startAt = this.selection == "even" ? 0 : 1;
for (let i = startAt; i <= number; i += 2) {
this.results.push(i + "\n");
}