2021-04-12 06:18:30 +02:00
|
|
|
// Copyright: Ankitects Pty Ltd and contributors
|
|
|
|
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|
|
|
|
2022-02-04 09:36:34 +01:00
|
|
|
import { naturalWholeUnit, TimespanUnit, unitAmount, unitSeconds } from "../lib/time";
|
2021-04-12 06:18:30 +02:00
|
|
|
|
|
|
|
function unitSuffix(unit: TimespanUnit): string {
|
|
|
|
switch (unit) {
|
|
|
|
case TimespanUnit.Seconds:
|
|
|
|
return "s";
|
|
|
|
case TimespanUnit.Minutes:
|
|
|
|
return "m";
|
|
|
|
case TimespanUnit.Hours:
|
|
|
|
return "h";
|
|
|
|
case TimespanUnit.Days:
|
|
|
|
return "d";
|
|
|
|
default:
|
|
|
|
// should not happen
|
|
|
|
return "";
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function suffixToUnit(suffix: string): TimespanUnit {
|
|
|
|
switch (suffix) {
|
|
|
|
case "s":
|
|
|
|
return TimespanUnit.Seconds;
|
|
|
|
case "h":
|
|
|
|
return TimespanUnit.Hours;
|
|
|
|
case "d":
|
|
|
|
return TimespanUnit.Days;
|
|
|
|
default:
|
|
|
|
return TimespanUnit.Minutes;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function minutesToString(step: number): string {
|
|
|
|
const secs = step * 60;
|
|
|
|
let unit = naturalWholeUnit(secs);
|
|
|
|
if ([TimespanUnit.Months, TimespanUnit.Years].includes(unit)) {
|
|
|
|
unit = TimespanUnit.Days;
|
|
|
|
}
|
2021-05-28 11:34:25 +02:00
|
|
|
const amount = Math.round(unitAmount(unit, secs));
|
2021-04-12 06:18:30 +02:00
|
|
|
|
|
|
|
return `${amount}${unitSuffix(unit)}`;
|
|
|
|
}
|
|
|
|
|
|
|
|
function stringToMinutes(text: string): number {
|
|
|
|
const match = text.match(/(\d+)(.*)/);
|
|
|
|
if (match) {
|
|
|
|
const [_, num, suffix] = match;
|
|
|
|
const unit = suffixToUnit(suffix);
|
|
|
|
const seconds = unitSeconds(unit) * parseInt(num, 10);
|
2021-12-15 09:46:26 +01:00
|
|
|
// should be representable as negative i32 seconds in a revlog
|
|
|
|
const capped_seconds = Math.min(seconds, 2 ** 31);
|
|
|
|
return capped_seconds / 60;
|
2021-04-12 06:18:30 +02:00
|
|
|
} else {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export function stepsToString(steps: number[]): string {
|
|
|
|
return steps.map(minutesToString).join(" ");
|
|
|
|
}
|
|
|
|
|
|
|
|
export function stringToSteps(text: string): number[] {
|
|
|
|
return (
|
|
|
|
text
|
|
|
|
.split(" ")
|
|
|
|
.map(stringToMinutes)
|
|
|
|
// remove zeros
|
|
|
|
.filter((e) => e)
|
|
|
|
);
|
|
|
|
}
|