diff --git a/frontend/src/helpers/toHHMMSS.test.ts b/frontend/src/helpers/toHHMMSS.test.ts new file mode 100644 index 0000000..7ea0c4a --- /dev/null +++ b/frontend/src/helpers/toHHMMSS.test.ts @@ -0,0 +1,49 @@ +import toHHMMSS from './toHHMMSS'; +import { Duration } from '../generated/google/protobuf/duration'; + +describe('toHHMMSS', () => { + it('renders correctly for 0ms', () => { + const duration: Duration = { seconds: 0, nanos: 0 }; + expect(toHHMMSS(duration)).toEqual('00:00'); + }); + + it('renders correctly for 500ms', () => { + const duration: Duration = { seconds: 0, nanos: 500_000_000 }; + expect(toHHMMSS(duration)).toEqual('00:00'); + }); + + it('renders correctly for 2700ms', () => { + const duration: Duration = { seconds: 27, nanos: 0 }; + expect(toHHMMSS(duration)).toEqual('00:27'); + }); + + it('renders correctly for 61s', () => { + const duration: Duration = { seconds: 61, nanos: 0 }; + expect(toHHMMSS(duration)).toEqual('01:01'); + }); + + it('renders correctly for 1200s', () => { + const duration: Duration = { seconds: 1200, nanos: 0 }; + expect(toHHMMSS(duration)).toEqual('20:00'); + }); + + it('renders correctly for 1201s', () => { + const duration: Duration = { seconds: 1201, nanos: 0 }; + expect(toHHMMSS(duration)).toEqual('20:01'); + }); + + it('renders correctly for 1h', () => { + const duration: Duration = { seconds: 3600, nanos: 0 }; + expect(toHHMMSS(duration)).toEqual('01:00:00'); + }); + + it('renders correctly for 1h1m1s', () => { + const duration: Duration = { seconds: 3661, nanos: 0 }; + expect(toHHMMSS(duration)).toEqual('01:01:01'); + }); + + it('renders correctly for 24h1s', () => { + const duration: Duration = { seconds: 86401, nanos: 0 }; + expect(toHHMMSS(duration)).toEqual('24:00:01'); + }); +}); diff --git a/frontend/src/helpers/toHHMMSS.ts b/frontend/src/helpers/toHHMMSS.ts new file mode 100644 index 0000000..6ff128b --- /dev/null +++ b/frontend/src/helpers/toHHMMSS.ts @@ -0,0 +1,17 @@ +import { Duration } from '../generated/google/protobuf/duration'; +import millisFromDuration from './millisFromDuration'; + +function toHHMMSS(dur: Duration): string { + const millis = millisFromDuration(dur); + let secs = Math.floor(millis / 1_000); + const hrs = Math.floor(secs / 3600); + const mins = Math.floor(secs / 60) % 60; + secs = secs % 60; + + return [hrs, mins, secs] + .map((v) => (v < 10 ? '0' + v : v)) + .filter((v, i) => v != '00' || i > 0) + .join(':'); +} + +export default toHHMMSS;