我在下面给出了一个简单的实现。这个想法是根据scoring function
和user data
为您的餐厅创建一个restaurant data.
,然后使用该功能为餐厅评分对餐厅进行排序。对后代进行评分,以在顶部获得最“最近”的餐厅。
您可以根据需要为分数分配权重。
// Given
const restaurants = [
{
cuisine: 'mexican',averageCost: '30',children: 'no'
},{
cuisine: 'italian',children: 'yes'
}
];
const user = [{ id: '1',city: 'Paris',cuisine: 'italian',allergic: 'no',budget: '50',hasChildren: 'yes' }];
const calculateScore = (user,restaurant) => {
// you can fine tune the values for the weights yourself
// asume that children score gives 1
const childrenScore = (user.hasChildren === restaurant.children) ? 1 : 0;
// asume that cuisine score gives 1
const cuisineScore = (user.cuisine === restaurant.cuisine) ? 1 : 0;
// asume that cost score gives the absolute difference
const costScore = Math.abs(parseInt(restaurant.averageCost) - parseInt(user.budget));
return childrenScore + cuisineScore + costScore;
}
const sortedRestaurants = restaurants.sort((rA,rB) => {
const rAScore = calculateScore(user[0],rA);
const rBScore = calculateScore(user[0],rB);
return rBScore - rAScore; // sort DESC by score
});
console.log(sortedRestaurants)
,
以下是您可以执行的操作的简短摘要。
const user = [{ id: '1',hasChildren: 'yes' }];
const restaurants = [
{
cuisine: 'mexican',children: 'no'
},{
cuisine: 'italian',children: 'yes'
}
]
const orderedRestaurants = restaurants.map(r => {
return {
...r,score: 0 +
(r.cuisine === user[0].cuisine ? 4 : 0) +
(r.averageCost <= user[0].budget ? 8 : 0) +
(r.children === 'no' && user[0].hasChildren === 'yes' ? 0 : 3)
}
}).sort((a,b) => b.score - a.score);
console.log(orderedRestaurants);
因此,我们需要根据特定条件为每家餐厅分配分数。我已经在函数中分配了权重,您可以将其移到对象之外以进行动态评分。
在此示例中,如果菜色符合用户的兴趣,我们将给他们4分;如果平均费用低于或等于预算,则给他们8分;如果用户有孩子和餐厅,则给他们3分允许孩子。随时根据需要编辑评分系统,但希望这可以帮助您入门。
本文链接:https://www.f2er.com/3163941.html