Last active
February 23, 2021 13:48
-
-
Save mholtzhausen/f380f9cfbc06e917c0ccffa238ea86a2 to your computer and use it in GitHub Desktop.
Timespan to Milliseconds
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 timespanToMs=(timeSpan)=>{ | |
let lut={'':1, ms:1, s:1000, m:60000, h:3600000, d: 86400000, w:604800000, y:31556952000 } | |
let ms=(`${timeSpan}`.match(/\d+[ywdhms]{0,2}\s?/g)).reduce((a,s)=>{ | |
let [,v,m] =s.match(/(\d+)([ywdhms]{0,2})/) | |
return a + (v * lut[m]) | |
},0) | |
return ms | |
} | |
let passTests=[ | |
timespanToMs('22s') === 22000, | |
timespanToMs('22d') === 1900800000, | |
timespanToMs(' 1y 4d 22s') === 31902574000 | |
].filter(test=>test===false).length===0 | |
console.log(passTests ? 'Passed all tests':'Something croaked') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment