我正在尝试计算机票上的危险因素
如果票证是作者的唯一票证,请加10% 如果门票价格低于该事件的平均门票价格,则存在风险 如果机票的价格比平均价格便宜X%,请在风险中加上X% 如果机票的价格比平均价格贵X%,请从风险中扣除X%,最高 扣除10% 如果票是在工作时间(9-17)添加的,则从风险中扣除10%;否则,将10%添加到 风险 如果票证上有> 3条评论,则增加5%的风险 最小风险为5%(没有任何风险),最大风险为95%。
以下算法应该起作用 但是try-catch可以使控制台记录错误
import Moment from 'moment'
export function getRiskfactor(tickets, ticket, users, comments) {
var riskFactor = 5,
counter = 0,
filterTickets = [],
date,
ticketPrice = ticket.price,
sum = 0,
percentage = 0;
try {
const userId = ticket.users.id;
filterTickets = tickets.filter(ticket => ticket.users.id == userId);
filterTickets = Object.values(filterTickets);
counter = filterTickets.length;
date = Moment(ticket.createdAt).format("H");
} catch (err) {
console.log("error");
}
// add 10%
if (counter === 1) riskFactor = 10;
// ticket lower and higher
filterTickets.forEach(function (ticket) {
sum = sum + ticket.price;
});
let average = parseInt(sum / counter, 10);
percentage = Math.abs(parseInt((average - ticketPrice) * 100 / average, 10));
if (ticketPrice < average) {
if (percentage > 10) riskFactor += 10;
else riskFactor += percentage;
} else {
if (percentage > 10) riskFactor -= 10;
else riskFactor -= percentage;
}
// business hours
if (date >= 9 && date <= 17) riskFactor -= 10;
else riskFactor += 10;
// comments more than 3
const filterComments = comments.filter(comment => comment.tickets.id == ticket.id)
if (filterComments.length > 3) riskFactor += 5;
// check if its les than 5% or more than 95%
if (riskFactor < 5) riskFactor = 5;
if (riskFactor > 95) riskFactor = 95;
return riskFactor;
}
我将算法加载到票证组件中 所有正确的数据都输入到这里
import React, { PureComponent } from "react";
import { connect } from "react-redux";
import Card from "material-ui/Card";
import CommentForm from "../comments/CommentForm";
import DisplayComments from "../comments/DisplayComments";
import { addComment, getAllComments } from "../../actions/comments";
import { getRiskfactor } from "../logic/calcRisk";
class TicketDetails extends PureComponent {
componentWillMount() {
this.props.getAllComments();
}
addComment = comment => {
this.props.addComment(comment);
};
render() {
const { ticket, tickets, comments } = this.props;
const { users } = ticket;
return <div>
<Card className="outer-card">
<h1>Ticket: {ticket.id}</h1>
<h2>Price: €{ticket.price}</h2>
<p>Description: {ticket.description}</p>
<h2>Image: {ticket.image}</h2>
<p>Risk: {getRiskfactor(tickets, ticket, users, comments)}%</p>
<hr />
</Card>
<DisplayComments data={this.props} />
<CommentForm onSubmit={this.addComment} />
</div>;
}
}
const mapStateToProps = state => {
return {
ticket: state.ticket,
users: state.users,
tickets: state.tickets,
comments: state.comments
};
};
const mapDispatchToProps = (dispatch) => {
return {
addComment: (comment) => dispatch(addComment(comment)),
getAllComments: () => dispatch(getAllComments())
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(TicketDetails);