Skip to content

Instantly share code, notes, and snippets.

@ebraminio
Last active February 8, 2022 12:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ebraminio/1f1f2ff51476243c7d3a5451bbc75ebb to your computer and use it in GitHub Desktop.
Save ebraminio/1f1f2ff51476243c7d3a5451bbc75ebb to your computer and use it in GitHub Desktop.
dead simple calculator for time
<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