我有运输公司,每个公司都有一定的条件来计算运输成本。
运输公司
success: function(response) {
$('#add-takeout-messages').html('<div class="alert alert-success">' +
'<button type="button" class="close" data-dismiss="alert">×</button>' +
'<strong><i class="glyphicon glyphicon-ok-sign"></i></strong> ' + response.messages +
'</div>');
}
条件计算器 :(使用lodash)
[
{
"status": {
"label": "Active",
"value": true
},
"categories": [
],
"_id": "5c3760435b30ef025d60aca7",
"title": "Company Name,
"type": "national",
"conditions": [
{
"priceRange": {
"min": 0.01,
"max": 30.01
},
"weightRange": {
"min": 0,
"max": 2
},
"deliveryDays": {
"label": "2 Days",
"value": 2
},
"status": {
"label": "Active",
"value": true
},
"paymentMethod": [
"all"
],
"_id": "5cadc06f02cce3054ccaecc5",
"cost": 5,
"extraWeightPrice": 1,
"eachUnit": 1
},
{
"priceRange": {
"min": 30.02,
"max": 100.01
},
"weightRange": {
"min": 0,
"max": 2
},
"deliveryDays": {
"label": "2 Days",
"value": 2
},
"status": {
"label": "Active",
"value": true
},
"paymentMethod": [
"all"
],
"_id": "5cadc06f02cce3054ccaecc4",
"cost": 5,
"extraWeightPrice": 1,
"eachUnit": 2
},
{
"priceRange": {
"min": 101,
"max": 50000
},
"weightRange": {
"min": 2,
"max": 50
},
"deliveryDays": {
"label": "2 Days",
"value": 2
},
"status": {
"label": "Active",
"value": true
},
"paymentMethod": [
"all"
],
"_id": "5cadc06f02cce3054ccaecc3",
"cost": 0
}
],
"__v": 0,
"payOnDelivery": 3.5
}
]
上面的方法工作正常,并且可以返回 const cost = 10;
const weight= 1;
const availableShippingConditions = shippings.map(shipping =>
shipping.conditions.filter(condition => {
return (
_.inRange(
cost,
condition.priceRange.min,
condition.priceRange.max
) &&
_.inRange(
weight,
condition.weightRange.min,
condition.weightRange.max
)
);
})[0]
);
,但我还需要计算一件事:
能够检查费用是否在condition[0]
之间,但priceRange
不在范围之内。我需要将weightRange
eachUnit
添加到最终结果中。
所以
extraWeightPrice
是cost
,而10€
是weight
,我们需要落入5kg
,但我们需要添加condition[0]
的额外重量成本,因为3€
变成eachUnit
(3
是weightRange.max
,重量是2
),而5
是1因此总运费应为extraWeightPrice
(8€
,因此cost:5
+ 5
)。期望的结果是仅在满足要求的条件下从3
数组返回shipping
对象,例如:
shippings
编辑: 我成功了,我想知道是否有更优雅的方法来实现这一目标。 (它将返回条件而不是公司)
{
"title": "Company Name",
"type": "national",
"conditions": [
{
"priceRange": {
"min": 0.01,
"max": 30.01
},
"weightRange": {
"min": 0,
"max": 2
},
"deliveryDays": {
"label": "2 Days",
"value": 2
},
"status": {
"label": "Active",
"value": true
},
"paymentMethod": [
"all"
],
"_id": "5cadc06f02cce3054ccaecc5",
"cost": 5, // THIS SHOULD BE 8
"extraWeightPrice": 1,
"eachUnit": 1
}
]
}