Issue
I have this simple calculation method which returns commission, I want to return calculated result from this precents array, I am trying to achieve this result with Array.find
method, problem is when I pass price 30
it's calculates from previous object {min: 0, max: 30, percent: 30}
but i want to calculation start from {min: 30, max: 40, percent: 29.70000000}
this object where min
value is 30
How can I achieve this?
function calculateCommisionValue(){
const percents = [{min: 0, max: 30, percent: 30}, {min: 30, max: 40, percent: 29.70000000},];
const result = percents.find(e => e.min <= 30 && e.max >= 30);
return 30 * result?.percent / 100
}
//result should be 27.82215064
Solution
The Array.find()
method will return the first element that satisfies your condition. As you have set both min
and max
condition to be inferior/superior or equal you will have an issue when the max of a condition is the same as the min of the next one, as it will always return the first one.
You should decide which value will be inclusive and which one will be exclusive. From your question I understand that you want a max exclusive and min inclusive, to select the lower percentage value when the price is 30.
You should remove the equal in the second consition as such:
function calculateCommisionValue(price: number) {
const percents = [{min: 0, max: 30, percent: 30}, {min: 30, max: 40, percent: 29.70000000},];
const result = percents.find(e => e.min <= price && e.max > price); // Remove the equal in the max consition
return price * result?.percent / 100
}
Answered By - P.E. Joëssel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.