Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* You are given a list of colored sheets given as text table with the following columns:
- Option 01 – [color of the sheet]|[win/loss]|[opponent name]
- Option 02 – [color of the sheet]|[name]|[player name]
- Option 03 – [color of the sheet]|[age]|[player age]
- The different columns will always be separated only by 'I' (there won't be any whitespaces).
- The rank of each player is calculated by the formula rank = (wins+1) / (losses+1).
- If a certain color sheet has no information about the name or the age of the player, you should not print it
- in the output. If there is no information about opponents, you must print '[]'.
- There might be many opponents with the same names. You will know that they are different ones by the color
- of the sheets. Write a JavaScript function to aggregate the results and print them as JSON string.
- Print at the console a JSON string that holds the age, the name, an array with the opponents (in alphabetical order)
- and rank of the player. The rank of the players should be rounded to 2 digits after the decimal point. */
- "use strict";
- function solve(args) {
- var notebook = {};
- function putRowInfoToObject(object, dataLine) {
- var color = dataLine[0];
- if (!(color in object)) {
- object[color] = {'age': '', 'name': '', 'opponents': [], 'rank': '', 'win': 1, 'loss': 1};
- }
- if (dataLine[1] == 'age') {
- object[color].age = dataLine[2];
- } else if (dataLine[1] == 'name') {
- object[color].name = dataLine[2];
- } else {
- object[color].opponents.push(dataLine[2]);
- (dataLine[1] == 'win') ? object[color].win += 1 : object[color].loss += 1;
- }
- }
- for (var i = 0; i < args.length; i += 1) {
- var line = args[i].split('|');
- putRowInfoToObject(notebook, line);
- }
- notebook = aggregateObject(notebook);
- console.log(JSON.stringify(notebook));
- function aggregateObject(object) {
- for (var key in object) {
- if (object.hasOwnProperty(key)) {
- if (object[key].age && object[key].name) {
- object[key].opponents.sort();
- object[key].rank =
- (object[key].win / object[key].loss).toFixed(2);
- delete object[key].win;
- delete object[key].loss;
- } else {
- delete object[key];
- }
- }
- }
- var newObject = {};
- var sortedColors = Object.keys(object).sort();
- for (var i = 0; i < sortedColors.length; i += 1) {
- if (object.hasOwnProperty(sortedColors[i])) {
- newObject[sortedColors[i]] = object[sortedColors[i]];
- }
- }
- return newObject;
- }
- }
- solve([
- 'purple|age|99',
- 'red|age|44',
- 'blue|win|pesho',
- 'blue|win|mariya',
- 'purple|loss|Kiko',
- 'purple|loss|Kiko',
- 'purple|loss|Kiko',
- 'purple|loss|Yana',
- 'purple|loss|Yana',
- 'purple|loss|Manov',
- 'purple|loss|Manov',
- 'red|name|gosho',
- 'blue|win|Vladko',
- 'purple|loss|Yana',
- 'purple|name|VladoKaramfilov',
- 'blue|age|21',
- 'blue|loss|Pesho'
- ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement