utils: add new timestamp function

This will be used to create suggested file names that include a timestamp.
This commit is contained in:
David Lechner
2022-03-01 14:42:45 -06:00
parent a87e2c664c
commit 12f34eb210
2 changed files with 30 additions and 1 deletions
+19 -1
View File
@@ -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]/);
});
});
+11
View File
@@ -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(/\..*$/, '');
}