settingsAccountsettings
Menusettings

Q: Tickets (task with JS Class)

+2 votes

Write a JS program that manages a database of tickets. A ticket has a destination, a price and a status. Your program will receive two argument – the first is an array of strings for ticket descriptions and the second is a string, representing a sorting criteria. The ticket descriptions have the following format:

<destinationName>|<price>|<status>

Store each ticket and at the end of execution return a sorted summary of all tickets, sorted by either destination, price or status, depending on the second parameter that your program received. Always sort in ascending order (default behavior for alphabetical sort). If two tickets compare the same, use order of appearance. See the examples for more information.

Input:

Your program will receive two parameters – an array of strings and a single string.

Output:

Return a sorted array of all the tickets that where registered.

Examples:

Sample Input:

['Philadelphia|94.20|available',
 'New York City|95.99|available',
 'New York City|95.99|sold',
 'Boston|126.20|departed'],
'destination'
 
Output:

[ Ticket { destination: 'Boston',
    price: 126.20,
    status: 'departed' },
  Ticket { destination: 'New York City',
    price: 95.99,
    status: 'available' },
  Ticket { destination: 'New York City',
    price: 95.99,
    status: 'sold' },
  Ticket { destination: 'Philadelphia',
    price: 94.20,
    status: 'available' } ]


Sample Input:

['Philadelphia|94.20|available',
 'New York City|95.99|available',
 'New York City|95.99|sold',
 'Boston|126.20|departed'],
'status'
 
Output:

[ Ticket { destination: 'Philadelphia',
    price: 94.20,
    status: 'available' },
  Ticket { destination: 'New York City',
    price: 95.99,
    status: 'available' },
  Ticket { destination: 'Boston',
    price: 126.20,
    status: 'departed' },
  Ticket { destination: 'New York City',
    price: 95.99,
    status: 'sold' } ]

asked in JavaScript category by user nikole

1 Answer

0 votes

My solution:

function solve(arr, criteria) {
    class Ticket {
        constructor(destination, price, status) {
            this.destination = destination;
            this.price = Number(price);
            this.status = status;
        }
    }
    let result = [];
    for (let i of arr) {
        let [destination, price, status] = i.split("|");
        let ticket = new Ticket(destination, price, status);
        result.push(ticket);
    }

    return result.sort((a, b) => a[criteria] > b[criteria]);
}

console.log(solve(['Philadelphia|94.20|available',
        'New York City|95.99|available',
        'New York City|95.99|sold',
        'Boston|126.20|departed'],
    'status'
));

/*console.log(solve(['Philadelphia|94.20|available',
 'New York City|95.99|available',
 'New York City|95.99|sold',
 'Boston|126.20|departed'],
 'destination'
 ));*/

 

answered by user mitko
...