Skip to content

Commit db32b64

Browse files
author
Hector Arce De Las Heras
committed
Add utility to convert duration to milliseconds
This commit introduces a new utility function that converts a duration value into a numeric value representing milliseconds. The duration input can be either a string or a number. If the duration is already a number, the function simply returns the input value. This utility will help standardize duration values across the codebase and improve the readability and maintainability of the code.
1 parent cfb0e29 commit db32b64

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed
Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,28 @@
1-
import { maxCountBetweenChars } from './string.utility';
1+
import { convertDurationToNumber, maxCountBetweenChars } from './string.utility';
22

33
describe('Cursor', () => {
44
it('maxCountBetweenChars - should return 3', () => {
55
const position = maxCountBetweenChars('#', '## - ## - ##');
66
expect(position).toBe(3);
77
});
8+
it('maxCountBetweenChars - should return 0', () => {
9+
const position = maxCountBetweenChars('#');
10+
expect(position).toBe(0);
11+
});
12+
it('convertDurationToNumber - should return 0', () => {
13+
const duration = convertDurationToNumber();
14+
expect(duration).toBe(0);
15+
});
16+
it('convertDurationToNumber - should return same value', () => {
17+
const duration = convertDurationToNumber(0.3);
18+
expect(duration).toBe(0.3);
19+
});
20+
it('convertDurationToNumber - should return convert string', () => {
21+
const duration = convertDurationToNumber('0.3s');
22+
expect(duration).toBe(300);
23+
});
24+
it('convertDurationToNumber - should return convert string (ms)', () => {
25+
const duration = convertDurationToNumber('300ms');
26+
expect(duration).toBe(300);
27+
});
828
});

src/utils/stringUtility/string.utility.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,24 @@ export const maxCountBetweenChars = (charCount: string, value?: string): number
2424
});
2525
return max;
2626
};
27+
28+
// The function is designed to convert a duration value, which could be a string or a number, into a numeric value representing milliseconds
29+
// If duration is already a number, it simply returns the number.
30+
export const convertDurationToNumber = (duration?: string | number): number => {
31+
if (!duration) {
32+
return 0;
33+
}
34+
if (typeof duration === 'number') {
35+
return duration;
36+
}
37+
38+
// Remove "ms" or "s" from the duration and convert it to a number
39+
const value = Number(duration.replace('ms', '').replace('s', ''));
40+
41+
// If the duration was in seconds, convert it to milliseconds
42+
if (duration.includes('s') && !duration.includes('ms')) {
43+
return value * 1000;
44+
}
45+
46+
return value;
47+
};

0 commit comments

Comments
 (0)