Diff

util/human/io.lua @ 13054:f4d7fe919969

util.human.io: Add parse_duration() method to parse a duration string Similar logic occurs throughout various modules in the codebase. We might even want a module:get_option_duration()??
author Matthew Wild <mwild1@gmail.com>
date Fri, 07 Apr 2023 14:14:53 +0100
parent 13051:164c2787901a
child 13067:386ca97bec5b
line wrap: on
line diff
--- a/util/human/io.lua	Fri Apr 07 14:03:24 2023 +0200
+++ b/util/human/io.lua	Fri Apr 07 14:14:53 2023 +0100
@@ -197,6 +197,17 @@
 	end, max_width;
 end
 
+local day = 86400;
+local multipliers = {
+	d = day, w = day * 7, m = 31 * day, mo = 31 * day, y = 365.2425 * day;
+	s = 1, mi = 60, h = 3600
+};
+local function parse_duration(duration_string)
+	local n, m = duration_string:lower():match("(%d+)%s*([dwmy]?.?)");
+	if not n then return nil; end
+	return tonumber(n) * ( multipliers[m] or 1 );
+end
+
 return {
 	getchar = getchar;
 	getline = getline;
@@ -210,4 +221,5 @@
 	term_width = term_width;
 	ellipsis = ellipsis;
 	table = new_table;
+	parse_duration = parse_duration;
 };