Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

dstoianov891 avatar dstoianov891 18 Точки

04 Bar Income Java Script Exercise

Привет,

Имам проблем с единия тест на задача Bar Income (имам 90/100 точки) , но не мога да разбера защо не минава последния тест?

https://pastebin.com/jG5fkNMx

1.*SoftUni Bar Income

Let`s take a break and visit the game bar at SoftUni. It is about time for the people behind the bar to go home and you are the person who has to draw the line and calculate the money from the products that were sold throughout the day. Until you receive a line with text "end of shift" you will be given lines of input. But before processing that line you have to do some validations first.

Each valid order should have a customer, product, count and a price:

  • Valid customer's name should be surrounded by '%' and must start with a capital letter, followed by lower-case letters
  • Valid product contains any word character and must be surrounded by '<' and '>'
  • Valid count is an integersurrounded by '|'
  • Valid price is any real number followed by '$'

The parts of a valid order should appear in the order given: customer, product, count and a price.

Between each part there can be other symbols, except ('|', '$', '%' and '.')

For each valid line print on the console: "{customerName}: {product} - {totalPrice}"

When you receive "end of shift" print the total amount of money for the day rounded to 2 decimal places in the following format: "Total income: {income}".

Input / Constraints

  • Strings that you have to process until you receive text "end of shift".

Output

  • Print all of the valid lines in the format "{customerName}: {product} - {totalPrice}"
  • After receiving "end of shift" print the total amount of money for the day rounded to 2 decimal places in the following format: "Total income: {income}"
  • Allowed working time / memory100ms / 16MB.

Examples

Input

Output

Comment

%George%<Croissant>|2|10.3$

%Peter%<Gum>|1|1.3$

%Maria%<Cola>|1|2.4$

end of shift

George: Croissant - 20.60

Peter: Gum - 1.30

Maria: Cola - 2.40

Total income: 24.30

Each line is valid, so we print each order, calculating the total price of the product bought.

At the end we print the total income for the day

 

%InvalidName%<Croissant>|2|10.3$

%Peter%<Gum>1.3$

%Maria%<Cola>|1|2.4

%Valid%<Valid>valid|10|valid20$

end of shift

Valid: Valid - 200.00

Total income: 200.00

On the first line, the customer name isn`t valid, so we skip that line.
The second line is missing product count.

The third line don`t have a valid price.

And only the forth line is valid

0
Programming Fundamentals
willystyle avatar willystyle 2472 Точки
Best Answer

В момента в който видиш, че грешката е ексепшън, а не грешен резултат, явно някъде се обръщаш към пропърти на undefined дата, т.е явно има случай в който регекса няма мач,а ти директно се обръщаш към групите, затова валидирай с една проверка дали има мач:

function solve(arr) { 
    arr.pop();
    let totalIncome = 0;
    arr.forEach((line) => {
        let pattern = /%([A-Z][a-z]+)%[^|$%.]*<(\w+)>[^|$%.]*\|([0-9]+)\|[^|$%.]*?([0-9]+\.?[0-9]*)\$/gm; 
        let result = pattern.exec(line);
	if (result) {
		let currentSum = Number(result[3]) * Number(result[4]);
		console.log(`${result[1]}: ${result[2]} - ${currentSum.toFixed(2)}`);
		totalIncome += currentSum;
	}        
    });
    console.log(`Total income: ${totalIncome.toFixed(2)}`); 
}

 

0
22/07/2019 13:48:32
dstoianov891 avatar dstoianov891 18 Точки

Много благодаря!

1
RosemaryMorissette avatar RosemaryMorissette 0 Точки

I heard bunches of the things about this game however, it is more than intriguing. The status of this game is likewise so high and I need to play this game and now I'm able to get best essay writing service uk reviews provides unique task. All things considered, this game affects me to play it and it is absolutely so fabulous game.

0
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.