Implement the class LeagueTable
.
This class is used to store results of soccer matches played, as well as return and display various stats about each team.
Match results will always be passed through the push
method as a string in the format "Home Team 0 - 0 Away Team"
.
When a new match ends and the scores are tallied, points are awarded to teams as follows:
3 points for a win 1 point for a draw 0 points for a loss
The class must have the following methods:
push(match_string) # insert a new match record get_points(team_name) # Returns the no. of points a team has, 0 by default get_goals_for(team_name) # Returns the no. of goals a team has scored, 0 by default get_goals_against(team_name) # Returns the no. of goals a team has conceded (had scored against them), 0 by default get_goal_difference(team_name) # Return the no. of goals a team has scored minus the no. of goals a team has conceded, 0 by default get_wins(team_name) # Return the no. of wins a team has, 0 by default get_draws(team_name) # Return the no. of draws a team has, 0 by default get_losses(team_name) # Return the no. of losses a team has, 0 by default
Example
lt = LeagueTable.new lt.push("Man Utd 3 - 0 Liverpool") puts lt.get_goals_for("Man Utd") => 3 puts lt.get_points("Man Utd") => 3 puts lt.get_points("Liverpool") => 0 puts lt.get_goal_difference("Liverpool") => -3 lt.push("Liverpool 1 - 1 Man Utd") puts lt.get_goals_for("Man Utd") => 4 puts lt.get_points("Man Utd") => 4 puts lt.get_points("Liverpool") => 1 puts lt.get_goals_against("Man Utd") => 1 puts lt.get_points("Tottenham") => 0
Test
lt.push("Man Utd 2 - 1 Liverpool")
lt.push("Liverpool 3 - 0 Man Utd")
Good luck!
This challenge comes from Mackay on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (4)
Javascript:
Well, I attempted this in Haskell. I took the liberty of making each function return a
Maybe
value, beingNothing
when the team isn't in the table instead of defaulting to 0. It uses a state monad to make storing and "mutating" data feasible. I decided to implement my own state monad here, but there are (better) implementations on stackage.Additionally, here's the example given in the post translated to my Haskell implementation:
Definitely some things missing and room for improvement but here we go. JavaScript.
Ruby, concise as usual: