-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlucky_bus_ticket.js
24 lines (18 loc) · 1002 Bytes
/
lucky_bus_ticket.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Description:
// In Russia regular bus tickets usually consist of 6 digits. The ticket is called lucky when the sum of the first three digits equals to the sum of the last three digits. Write a function to find out whether the ticket is lucky or not. Return true if so, otherwise return false. Consider that input is always a string. Watch examples below.
//
// isLucky('123321') => 1+2+3 = 3+2+1 => true // The ticket is lucky
// isLucky('12341234') => false // Only six-digit numbers allowed :(
// isLucky('12a21a') => false // Letters are not allowed :(
// isLucky('100200') => false // :(
// isLucky('22') => false // :(
// isLucky('abcdef') => false // :(
// SOLUTION:
function isLucky(ticket) {
if (ticket.length !== 6 || !/^\d{6}$/.test(ticket)) {
return false;
}
const sumFirst = ticket.slice(0, 3).split('').reduce((acc, el) => acc + +el, 0);
const sumLast = ticket.slice(3, 6).split('').reduce((acc, el) => acc + +el, 0);
return sumFirst === sumLast;
}