I wrote a code with condition and for me I have lots a repetition of similar code. Can I make this code more efficient with a refactor ? After some research, that's the best that I can do that's just a part of the code, not the entire https://codepen.io/manofthelake/pen/GRyMzgW?editors=1010
const firstNumber = 50
const lastNumber = 1000
const defaultMinNumber = firstNumber + Math.round((lastNumber - firstNumber) / 2 )
const selection = {
min: null
max: null
}
if (Object.values(selection).every(s => s === null)) {
selection.min = defaultMinNumber
selection.max = lastNumber
}
else if (selection.min < firstNumber) {
savedSelection = {...selection}
selection.min = (selection.max > firstNumber) ? firstNumber: defaultMinNumber
selection.max = (selection.max > firstNumber) ? selection.max : lastNumber
}
else if (Object.values(savedSelection).every(s => s !== null)) {
selection.min = (savedSelection.max > firstNumber) ? selection.min : defaultMinNumber
selection.max = (savedSelection.max > firstNumber) ? selection.max : lastNumber
}
Observations/Refactoring :
What is the different between lastNumber and defaultMinNumber as both will return same value. Looks like something has been missed in that calculation.
Instead of loop on each and every element you can use Nullish coalescing operator (??) which returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
selection.min ?? defaultMinNumber
selection.max ?? lastNumber