I have a super simple function that returns a text label for a range of the input
function fn(amount) {
if (amount >= 1 && amount <= 10) return 'small'
if (amount >= 11 && amount <= 20) return 'medium'
if (amount >= 21 && amount <= 30) return 'large'
}
And this is an "over-engineered" version of the function but I think it scales better
const labelByAmounts = [
{ min: 1, max: 10, label: 'small' },
{ min: 11, max: 20, label: 'medium' },
{ min: 21, max: 30, label: 'large' },
]
function fn2(amount) {
return labelByAmounts.find(
(labelByAmount) =>
amount >= labelByAmount.min && amount <= labelByAmount.max
).label
}
The idea is that the second approach is a table-driven method (learned from the book code complete or also called strategy pattern?) which is more modifiable and extensible. But I find the table lookup is still bit awkward since you have to loop through the list and compare the min
and max
.
Looking for suggestions to:
- simplify the lookup process
- improve the time complexity if the list grows to have thousands of records? Right I think the time complexity for both approaches is o(1) but I guess there might be ways to improve the constant factor?
- improve the readability
- maybe a different but better approach?
- Lastly, is there a way to benchmark these different variants against large dataset to see which one is the fastest (in a specific environment, i.e. browser)?
['small','medium','large'][ Math.int( (amount-1)/10 ) ]
. \$\endgroup\$