基于比分字段生成三种比赛结果判定公式的技术需求
Determine Match Result from Score String
I have this state data containing match information, and I need to write a formula to determine the match result based on the score field (like '3:0'). The rules are:
- If the first number in the score is greater than the second → result is 'won'
- If they are equal → result is 'drew'
- If the first number is less than the second → result is 'loss'
Here's my existing data:
state = { data: [ createData('23 May 2017', 'Seniors', 'Brazil', '90 mins', '3:0'), createData('14 May 2017', 'Seniors', 'Italy', '45 mins', '0:0'), createData('14 Nov 2016', 'Seniors', 'Germany', '0 mins', '0:2') ], };
Step 1: Build a helper function to parse scores and return results
Let's start with a reusable function that takes a score string, breaks it down, and applies your rules. It handles basic edge cases too, like malformed score formats:
function getMatchResult(score) { // Split the score string, trim any extra spaces, and convert to numbers const [ourScore, opponentScore] = score.split(':').map(s => Number(s.trim())); // Handle invalid score formats (optional but useful) if (isNaN(ourScore) || isNaN(opponentScore)) { return 'invalid'; // Adjust this to your error handling needs } // Apply the result logic if (ourScore > opponentScore) { return 'won'; } else if (ourScore === opponentScore) { return 'drew'; } else { return 'loss'; } }
Step 2: Apply the function to your existing match data
You can use Array.map() to attach the result to each entry in your state.data array. Assuming each object returned by createData includes a score property (the fifth parameter), here's how to update your data:
// Add the result to each match entry const matchesWithResults = state.data.map(match => ({ ...match, result: getMatchResult(match.score) })); // Check the output console.log(matchesWithResults);
Example Output for Your Sample Data
Running this code would generate results like:
- Brazil match →
'won' - Italy match →
'drew' - Germany match →
'loss'
Quick Notes
- If your score strings might have inconsistent spacing (like
'3 : 0'), the.trim()in the helper function ensures numbers are parsed correctly. - The
'invalid'return value is optional—feel free to replace it with an empty string, null, or custom error message if needed.
内容的提问来源于stack exchange,提问作者Tom Rudge
相关产品推荐
相关产品推荐

