Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* You are given a sequence of soccer results in format "homeTeam / awayTeam: homeGoals-awayGoals".
- Your task is to write a JavaScript function that prints at the console a JSON string that holds the teams,
- and for each team goals scored, goals conceded and a list of teams that had a match with this team in
- the same format like at the below examples. Print at the console a JSON string that holds the teams
- (in alphabetical order) and for each team goals scored, goals conceded and a list of teams that had
- a match with this team (in alphabetical order). Duplicated teams should be printed once only
- (all strings are case-sensitive). */
- "use strict";
- function sorterSoccerResults(args) {
- var soccerMap = {};
- var pattern = /([^/]+)\/([^:]+):([^-]+)-\s*(\d{1,2})/g;
- for (var i = 0; i < args.length; i += 1) {
- var matcher, homeTeam, awayTeam, homeGoals, awayGoals;
- while (matcher = pattern.exec(args[i])) {
- homeTeam = matcher[1].trim();
- awayTeam = matcher[2].trim();
- homeGoals = Number(matcher[3]);
- awayGoals = Number(matcher[4]);
- }
- addingInfoToObject(soccerMap, homeTeam, awayTeam, homeGoals, awayGoals);
- addingInfoToObject(soccerMap, awayTeam, homeTeam, awayGoals, homeGoals);
- }
- function addingInfoToObject(object, homeTeam, awayTeam, homeGoals, awayGoals) {
- if (!(object.hasOwnProperty(homeTeam))) {
- object[homeTeam] = { 'goalsScored': 0, 'goalsConceded': 0, 'matchesPlayedWith': [] };
- }
- object[homeTeam].goalsScored += homeGoals;
- object[homeTeam].goalsConceded += awayGoals;
- if (object[homeTeam].matchesPlayedWith.indexOf(awayTeam) < 0) {
- object[homeTeam].matchesPlayedWith.push(awayTeam);
- }
- }
- function sortInfoInObject(object) {
- var sortedHomeTeams = Object.keys(object).sort();
- var sortedObject = {};
- for (var i = 0; i < sortedHomeTeams.length; i += 1) {
- if (object.hasOwnProperty(sortedHomeTeams[i])) {
- object[sortedHomeTeams[i]].matchesPlayedWith.sort();
- sortedObject[sortedHomeTeams[i]] = object[sortedHomeTeams[i]];
- }
- }
- return sortedObject;
- }
- soccerMap = sortInfoInObject(soccerMap);
- console.log(JSON.stringify(soccerMap));
- }
- sorterSoccerResults([
- "Germany / Argentina: 1-0",
- "Brazil / Netherlands: 0-3",
- "Netherlands / Argentina: 0-0",
- "Brazil / Germany: 1-7",
- "Argentina / Belgium: 1-0",
- "Netherlands / Costa Rica: 0-0",
- "France / Germany: 0-1",
- "Brazil / Colombia: 2-1" ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement