| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="HumanFriendlyTimeSpanQuantizer.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System.Collections.Generic; |
| | | 8 | | using System.Linq; |
| | | 9 | | using MyNet.Primitives; |
| | | 10 | | using MyNet.Temporal.Decomposition; |
| | | 11 | | |
| | | 12 | | namespace MyNet.Humanizer.Temporal; |
| | | 13 | | |
| | | 14 | | /// <summary> |
| | | 15 | | /// Rounds decomposed values to friendlier thresholds (for instance 59 seconds to 1 minute). |
| | | 16 | | /// </summary> |
| | | 17 | | /// <example> |
| | | 18 | | /// [59 seconds] becomes [1 minute]. |
| | | 19 | | /// [1 hour, 59 minutes] can become [2 hours]. |
| | | 20 | | /// </example> |
| | | 21 | | public sealed class HumanFriendlyTimeSpanQuantizer : ITimeSpanQuantizer |
| | | 22 | | { |
| | | 23 | | /// <summary> |
| | | 24 | | /// Gets the default quantizer instance. |
| | | 25 | | /// </summary> |
| | 3 | 26 | | public static HumanFriendlyTimeSpanQuantizer Default { get; } = new(); |
| | | 27 | | |
| | | 28 | | /// <inheritdoc/> |
| | | 29 | | public IReadOnlyList<TimeUnitValue> Quantize(IReadOnlyList<TimeUnitValue> values) |
| | | 30 | | { |
| | 15 | 31 | | if (values.Count <= 1) |
| | 9 | 32 | | return values; |
| | | 33 | | |
| | 6 | 34 | | var ordered = values.OrderByDescending(x => x.Unit).ToList(); |
| | 6 | 35 | | var dict = ordered.ToDictionary(x => x.Unit, x => x.Value); |
| | | 36 | | |
| | 30 | 37 | | for (var i = ordered.Count - 1; i > 0; i--) |
| | | 38 | | { |
| | 9 | 39 | | var currentUnit = ordered[i].Unit; |
| | 9 | 40 | | var nextUnit = ordered[i - 1].Unit; |
| | 9 | 41 | | var currentValue = dict[currentUnit]; |
| | 9 | 42 | | var threshold = GetThreshold(currentUnit); |
| | | 43 | | |
| | 9 | 44 | | if (threshold > 0 && currentValue >= threshold) |
| | | 45 | | { |
| | 6 | 46 | | dict[nextUnit]++; |
| | 6 | 47 | | dict[currentUnit] = 0; |
| | | 48 | | |
| | | 49 | | // Drop smaller details after promoting to a bigger unit. |
| | 18 | 50 | | for (var j = i + 1; j < ordered.Count; j++) |
| | 3 | 51 | | dict[ordered[j].Unit] = 0; |
| | | 52 | | } |
| | | 53 | | } |
| | | 54 | | |
| | 6 | 55 | | return ordered.ConvertAll(x => x with { Value = dict[x.Unit] }); |
| | | 56 | | } |
| | | 57 | | |
| | | 58 | | private static int GetThreshold(TimeUnit unit) |
| | 9 | 59 | | => unit switch |
| | 9 | 60 | | { |
| | 0 | 61 | | TimeUnit.Millisecond => 500, |
| | 6 | 62 | | TimeUnit.Second => 59, |
| | 3 | 63 | | TimeUnit.Minute => 59, |
| | 0 | 64 | | TimeUnit.Hour => 23, |
| | 0 | 65 | | TimeUnit.Day => 6, |
| | 0 | 66 | | TimeUnit.Week => 3, |
| | 0 | 67 | | TimeUnit.Month => 11, |
| | 0 | 68 | | _ => 0 |
| | 9 | 69 | | }; |
| | | 70 | | } |
| | | 71 | | |