Przeglądaj źródła

Added RunStatistics_withTraverse

Piotr Czajkowski 2 lat temu
rodzic
commit
28d07941c8

+ 35 - 0
analyzeJSON/Statistics.cs

@@ -0,0 +1,35 @@
+using System.Collections.Generic;
+using Newtonsoft.Json.Linq;
+using System.Linq;
+
+namespace analyzeJSON
+{
+    public record WordCountResult<T>(T NodeCounts, int TotalWordCount);
+    public class Statistics
+    {
+        private readonly Dictionary<string, int> nodeCounts = new Dictionary<string, int>();
+        private int totalWordCount;
+
+        private static int CountWords(string text)
+        {
+            var words = text.Split(" ");
+            return words.Count(x => !string.IsNullOrWhiteSpace(x));
+        }
+
+        public void RunStatistics(JToken token)
+        {
+            if (token.Type != JTokenType.String)
+                return;
+
+            var tokenName = AnalyzeJSON.GetNameFromPath(token.Path);
+            if (!nodeCounts.ContainsKey(tokenName))
+                nodeCounts.Add(tokenName, 0);
+
+            var wordCount = CountWords(token.Value<string>());
+            nodeCounts[tokenName] += wordCount;
+            totalWordCount += wordCount;
+        }
+
+        public WordCountResult<Dictionary<string, int>> Result => new(nodeCounts, totalWordCount);
+    }
+}

+ 21 - 0
analyzeJSONTests/StatisticsIntegrationTests.cs

@@ -0,0 +1,21 @@
+using Xunit;
+using analyzeJSON;
+
+namespace analyzeJSONTests
+{
+    public class StatisticsIntegrationTests
+    {
+        private static readonly string testFile = @"testFiles/complex.json";
+
+        [Fact]
+        public void RunStatistics_withTraverse()
+        {
+            var test = new AnalyzeJSON(testFile);
+            var stats = new Statistics();
+
+            test.Traverse((token) => stats.RunStatistics(token));
+            Assert.Equal(10, stats.Result.NodeCounts.Count);
+            Assert.Equal(165, stats.Result.TotalWordCount);
+        }
+    }
+}