OpenSlides/client/src/app/core/ui-services/duration.service.ts

82 lines
2.5 KiB
TypeScript
Raw Normal View History

import { Injectable } from '@angular/core';
/**
* Helper service to convert numbers to time representation
* and vice versa
*
* @example
* ```ts
* // will result in 70
* const a = this.durationService.stringToDuration('01:10h');
*
* // will also result in 70
* const b = this.durationService.stringToDuration('01:10');
*
2019-02-14 16:02:18 +01:00
* // will also result in 89 (interpret as seconds)
* const b = this.durationService.stringToDuration('01:20 m', 'm');
*
* // will result in 0
* const c = this.durationService.stringToDuration('01:10b');
* ```
*
* @example
* ```ts
* // will result in 01:10 h
2019-03-06 16:54:00 +01:00
* const a = this.durationService.durationToString(70, 'h');
2019-02-14 16:02:18 +01:00
*
* // will result in 00:30 m (30 is interpreted as seconds)
2019-03-06 16:54:00 +01:00
* const a = this.durationService.durationToString(30, 'm');
* ```
*/
@Injectable({
providedIn: 'root'
})
export class DurationService {
/**
* Constructor
*/
public constructor() {}
/**
2019-02-14 16:02:18 +01:00
* Transform a duration string to duration in minutes or seconds. This depends on the
* provided suffix for the input.
*
* @param durationText the text to be transformed into a duration
2019-02-14 16:02:18 +01:00
* @param suffix may be 'h' or 'm' for hour or minute. This character will be removed
* from the duration text.
* @returns time in minutes or seconds or 0 if values are below 0 or no parsable numbers
*/
2019-02-14 16:02:18 +01:00
public stringToDuration(durationText: string, suffix: 'h' | 'm' = 'h'): number {
const splitDuration = durationText.replace(suffix, '').split(':');
let time: number;
if (splitDuration.length > 1 && !isNaN(+splitDuration[0]) && !isNaN(+splitDuration[1])) {
time = +splitDuration[0] * 60 + +splitDuration[1];
} else if (splitDuration.length === 1 && !isNaN(+splitDuration[0])) {
time = +splitDuration[0];
}
if (!time || time < 0) {
time = 0;
}
return time;
}
/**
2019-02-14 16:02:18 +01:00
* Converts a duration number (given in minutes or seconds)
*
2019-03-06 16:54:00 +01:00
* @param duration value in minutes or seconds (60 units being the next bigger unit)
* @param suffix any suffix to add.
* @returns a more human readable time representation
*/
2019-03-06 16:54:00 +01:00
public durationToString(duration: number, suffix: 'h' | 'm'): string {
2019-02-14 16:02:18 +01:00
const major = Math.floor(duration / 60);
const minor = `0${duration % 60}`.slice(-2);
if (!isNaN(+major) && !isNaN(+minor)) {
return `${major}:${minor} ${suffix}`;
} else {
return '';
}
}
}