Last active
February 8, 2022 12:35
-
-
Save ebraminio/1f1f2ff51476243c7d3a5451bbc75ebb to your computer and use it in GitHub Desktop.
dead simple calculator for time
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
<textarea id=input style="width: 50%; height: 5em; white-space: pre" oninput="result.innerText = calculate(this.value)"></textarea> | |
<div id=result></div> | |
<script> | |
window.onload = () => { | |
input.value = '1d 2h 3m 4s + 4h 5s - 2030s + 28h'; | |
input.dispatchEvent(new Event('input')) | |
}; | |
function calculate(input) { | |
const units = Object.entries({ d: 86400, h: 3600, m: 60, s: 1 }); | |
const seconds = eval( | |
input.replace( | |
/[\d\w\s]+/g, | |
x => '(' + units.reduce((acc, unit) => acc.replace(new RegExp('(\\d+)' + unit[0]), '+$1*' + unit[1]), x) + ')' | |
) | |
); | |
const result = units.reduce( | |
([result, reminder], unit) => [result + Math.floor(reminder / unit[1]) + unit[0] + ' ', reminder % unit[1]], ['', seconds] | |
)[0]; | |
return result + '\n' + units.map(unit => (seconds / unit[1]) + ' ' + unit[0]).join('\n'); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment