I have an array of ranges as you can see in the snippet. when user select certain number from dropdown I want to remove that number from the range and return new ranges,
Everything is working as per my expectation but I think, I have over coded and used too many if else statements in my code. I was wondering if there is any better way to do it?
If yes please let me know, if Javascript has any methods to make this simple and reduce the amount of code.
var ranges = [
{start: 1, end: 100},
{start: 150, end: 300},
{start: 400, end: 500},
{start: 550, end: 650},
];
function onSelect(event) {
let newRange = [];
let HMID = parseInt(document.getElementById("mySelect").value);
for (let range of ranges) {
if ((HMID > range.start) && (HMID < range.end)) {
newRange.push({start: range.start, end: (HMID - 1)});
newRange.push({start: (HMID + 1), end: range.end});
} else if (HMID === range.start) {
newRange.push({start: (range.start + 1), end: range.end});
} else if (HMID === range.end) {
newRange.push({start: range.start, end: (range.end - 1)});
} else {
newRange.push(range);
}
}
console.log(JSON.stringify(newRange));
}
function onSelectAdd() {
let newRange = [];
let HMID = parseInt(document.getElementById("mySelectAdd").value);
for (let i = 0; i < (ranges.length); i++) {
let start, end;
if (HMID == (ranges[i].start -1)) {
start = HMID;
end = ranges[i].end;
newRange.push({start: start, end: end});
} else if (HMID == (ranges[i].end + 1)) {
start = ranges[i].start;
if (ranges.length === (i + 1)) {
end = HMID;
} else {
if (HMID == (ranges[i+1].start - 1)) {
end = ranges[i+1].end;
i++;
} else {
end = ranges[i].end;
}
}
newRange.push({start: start, end: end});
} else {
newRange.push({start: ranges[i].start, end: ranges[i].end});
}
}
console.log(JSON.stringify(newRange));
}
<p>Remove item</p>
<select id="mySelect" onchange="onSelect()">
<option value="1">1</option>
<option value="150">150</option>
<option value="450">450</option>
<option value="650">650</option>
</select>
<p>Add removed item</p>
<select id="mySelectAdd" onchange="onSelectAdd()">
<option value="1">1</option>
<option value="150">150</option>
<option value="450">450</option>
<option value="650">650</option>
</select>
EDIT: I am looking only for logical and functional code review. Please don't comment on syntax and variable names. Thanks.