Created
April 19, 2022 08:07
-
-
Save nkhil/50b106572126d8b2bf986ce784cd8495 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function parseLogs(logs) { | |
const logsArray = logs.split('\n').map(eachLog => eachLog.split(',')) | |
const normalisedArray = normaliseArray(logsArray) | |
const logsWithSeconds = normalisedArray.map(([timestamp, phoneNumber]) => | |
[calculateTotalSeconds(timestamp), phoneNumber]) | |
const grouped = groupByPhoneNumber(logsWithSeconds) | |
const phoneNumberWithLargestTotal = getPhoneNumberWithLargestTotalSeconds(grouped) | |
grouped[phoneNumberWithLargestTotal] = 0 | |
return calculateTotalBill(logsWithSeconds, phoneNumberWithLargestTotal) | |
} | |
function normaliseArray(logsArray) { | |
const lastElementIdx = logsArray.length - 1 | |
if (logsArray[lastElementIdx].length === 1 && logsArray[lastElementIdx][0] === '') { | |
return logsArray.slice(0, -1) | |
} | |
return logsArray | |
} | |
function calculateTotalBill(logsWithSeconds, phoneNumberWithLargestTotal) { | |
const FIVE_MINUTES = 5 * 60 | |
return logsWithSeconds.reduce((acc, [totalSeconds, phoneNumber]) => { | |
if (phoneNumber !== phoneNumberWithLargestTotal) { | |
switch (true) { | |
case totalSeconds < FIVE_MINUTES: | |
acc = acc + totalSeconds * 3 | |
break; | |
case totalSeconds >= FIVE_MINUTES: | |
const numOfMinutes = Math.trunc(totalSeconds / 60) | |
acc = acc + numOfMinutes * 150 | |
default: | |
break; | |
} | |
} | |
return acc | |
}, 0) | |
} | |
function calculateTotalSeconds(timestamp) { | |
const [hours, minutes, seconds] = timestamp.split(':') | |
return Number(hours) * 60 * 60 + Number(minutes) * 60 + Number(seconds) | |
} | |
function groupByPhoneNumber(logs) { | |
return logs.reduce((acc, val) => { | |
const [ seconds, phoneNumber ] = val | |
if (!acc.hasOwnProperty(phoneNumber)) { | |
acc[phoneNumber] = seconds | |
} else { | |
acc[phoneNumber] = acc[phoneNumber] + seconds | |
} | |
return acc | |
}, {}) | |
} | |
function getPhoneNumberWithLargestTotalSeconds(logs) { | |
const logsArray = Object.keys(logs).map(key => [key, logs[key]]) | |
let largestTotal = 0 | |
let phoneNumberWithLargestTotal = '' | |
logsArray.forEach(([phoneNumber, totalSeconds]) => { | |
if (totalSeconds > largestTotal) { | |
largestTotal = totalSeconds | |
phoneNumberWithLargestTotal = phoneNumber | |
} else if (totalSeconds === largestTotal) { | |
if (Number(phoneNumber.replace(/-/g, '')) < Number(phoneNumberWithLargestTotal.replace(/-/g, ''))) { | |
phoneNumberWithLargestTotal = phoneNumber | |
} | |
} | |
}) | |
return phoneNumberWithLargestTotal | |
} | |
module.exports = parseLogs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment