Skip to content

Commit

Permalink
Add number parser (#39)
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcusOtter authored Oct 30, 2023
1 parent deecf2a commit 51d7bbb
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion InnerTube/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ namespace InnerTube;
public static class Utils
{
public static IFormatter Formatter = new HtmlFormatter();
private static readonly Regex NotDigitsRegex = new(@"\D");

public static T? GetFromJsonPath<T>(this JToken json, string jsonPath)
{
Expand Down Expand Up @@ -164,6 +165,23 @@ public static TimeSpan ParseDuration(string duration)
timeSpan = TimeSpan.Zero;
return timeSpan;
}

/// <summary>
/// Parses a string to a <see cref="ulong"/> by removing all non-digit characters first.<br /><br />
/// Negative numbers are not supported. If string contains no digits, returns 0.
/// </summary>
/// <param name="input">The string to parse, e.g. "10,341 views".</param>
/// <returns>The number, e.g. 10341.</returns>
/// <exception cref="OverflowException">
/// The number is less than <see cref="ulong.MinValue"/> or greater than <see cref="ulong.MaxValue"/>.
/// </exception>
public static ulong ParseNumber(string input)
{
input = NotDigitsRegex.Replace(input, "");
return string.IsNullOrWhiteSpace(input)
? 0
: ulong.Parse(input);
}

public static string GetParams(this ChannelTabs tab) =>
tab switch
Expand Down Expand Up @@ -323,4 +341,4 @@ public static string PackCommentsContinuation(string videoId, CommentsContext.Ty

return ToBase64UrlString(continuation.ToByteArray());
}
}
}

0 comments on commit 51d7bbb

Please sign in to comment.