From 12f34eb210f723b8d40f2ecd03afe289848ba64c Mon Sep 17 00:00:00 2001 From: David Lechner Date: Tue, 1 Mar 2022 14:42:45 -0600 Subject: [PATCH] utils: add new timestamp function This will be used to create suggested file names that include a timestamp. --- src/utils/index.test.ts | 20 +++++++++++++++++++- src/utils/index.ts | 11 +++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/utils/index.test.ts b/src/utils/index.test.ts index 09b19f59..fb80543b 100644 --- a/src/utils/index.test.ts +++ b/src/utils/index.test.ts @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MIT // Copyright (c) 2020 The Pybricks Authors -import { assert, defined, ensureError, hex, maybe } from '.'; +import { assert, defined, ensureError, hex, maybe, timestamp } from '.'; test('assert', () => { const assertTrue = jest.fn(() => assert(true, 'should not throw')); @@ -44,3 +44,21 @@ test('ensureError', () => { stringToError.toHaveProperty('name', 'Error'); stringToError.toHaveProperty('message', stringToErrorMessage); }); + +describe('timestamp', () => { + it('should not contain spaces', () => { + expect(timestamp()).not.toContain(' '); + }); + + it('should not contain colons', () => { + expect(timestamp()).not.toContain(':'); + }); + + it('should not contain periods', () => { + expect(timestamp()).not.toContain('.'); + }); + + it('should not contain letters', () => { + expect(timestamp()).not.toMatch(/[A-Za-z]/); + }); +}); diff --git a/src/utils/index.ts b/src/utils/index.ts index d85b9bda..23c8297b 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -63,3 +63,14 @@ export function ensureError(err: unknown): Error { return Error(String(err)); } + +/** + * Gets a timestamp with second resolution suitable for use in a filename. + */ +export function timestamp(): string { + return new Date() + .toISOString() + .replace('T', '_') + .replaceAll(':', '-') + .replace(/\..*$/, ''); +}