Last active
May 28, 2021 07:41
-
-
Save daviddamilola/91eba929789ec16404b7ae9a213e5ede to your computer and use it in GitHub Desktop.
get min diff between time items in array
This file contains 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
const getDiff = (date1, date2) => { | |
let diff = date1 - date2 | |
const result = (diff/60) | |
return result; | |
} | |
const parseToSeconds = (time)=> { | |
const hrsMins = time.split(':') | |
const secHrs = parseInt(hrsMins[0],10) * 60 * 60 | |
const secMins = parseInt(hrsMins[1],10) * 60 | |
return secHrs + secMins | |
} | |
const helpEsther = (esthersInput=[]) => { | |
if(esthersInput.length < 1) return 0; | |
if(esthersInput.length === 1) return parseToSeconds(esthersInput[0])/60; | |
//filter out invalid values | |
const validRegex = /^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/; | |
const cleanedInput = esthersInput.filter(each => validRegex.test(each)); | |
const timeDiffs = []; | |
const sortAndSaveTime = (firstTime, secondTime) => { | |
const date1 = parseToSeconds(firstTime) | |
const date2 = parseToSeconds(secondTime) | |
if(date1 > date2){ | |
timeDiffs.push(getDiff(date1,date2)) | |
return 1 | |
}else if(date2 > date1){ | |
timeDiffs.push(getDiff(date2, date1)) | |
return -1 | |
} | |
timeDiffs.push(0) | |
return 0 | |
} | |
cleanedInput.sort(sortAndSaveTime) | |
return Math.min(...timeDiffs) | |
} | |
console.log(helpEsther(['16:00','12:01', '12:02', '12:20'])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello @daviddamilola, congratulations 🎉 your solution has been selected as one of the winning solutions in Week 7 of #AlgorithmFridays.
Your solution is clean and readable and passed the test cases. I particularly like how you structured your code into separate functions. Really neat!
Out of the many winning solutions, only 3 will be selected for the $20 prize in a raffle draw. The raffle draw will hold today, Friday May 28 at 3.00pm WAT (7.00 am PST)
If you are interested in being a part of the raffle draw, please send me a DM on Twitter @meekg33k so I can share the event invite with you.
NB: Only solutions of participants who indicated interest in the raffle draw will be considered.
Thanks once again for participating and see you later today for Week 8 of #AlgorithmFridays.