Skip to content

Commit

Permalink
[Backend] Replace .ContainsKey with .TryGetValue/.TryAdd (#3052)
Browse files Browse the repository at this point in the history
  • Loading branch information
imnasnainaec authored Jun 5, 2024
1 parent c6f2191 commit 6302b3c
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 59 deletions.
11 changes: 3 additions & 8 deletions Backend/Controllers/UserRoleController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,11 @@ public async Task<IActionResult> GetCurrentPermissions(string projectId)
return NotFound($"user: {userId}");
}

if (!user.ProjectRoles.ContainsKey(projectId))
if (!user.ProjectRoles.TryGetValue(projectId, out var roleId))
{
return Ok(new List<Permission>());
}
var userRole = await _userRoleRepo.GetUserRole(projectId, user.ProjectRoles[projectId]);
var userRole = await _userRoleRepo.GetUserRole(projectId, roleId);
if (userRole is null)
{
return Ok(new List<Permission>());
Expand Down Expand Up @@ -231,12 +231,7 @@ public async Task<IActionResult> UpdateUserRole(
return NotFound(userId);
}

string userRoleId;
if (changeUser.ProjectRoles.ContainsKey(projectId))
{
userRoleId = changeUser.ProjectRoles[projectId];
}
else
if (!changeUser.ProjectRoles.TryGetValue(projectId, out var userRoleId))
{
// Generate the userRole
var usersRole = new UserRole { ProjectId = projectId };
Expand Down
31 changes: 10 additions & 21 deletions Backend/Services/LiftService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -145,11 +145,8 @@ public void SetExportInProgress(string userId, bool isInProgress)
/// <summary> Query whether user has an in-progress export. </summary>
public bool IsExportInProgress(string userId)
{
if (!_liftExports.ContainsKey(userId))
{
return false;
}
return _liftExports[userId] == InProgress;
_liftExports.TryGetValue(userId, out var exportPath);
return exportPath == InProgress;
}

/// <summary> Store filePath for a user's Lift export. </summary>
Expand All @@ -163,12 +160,8 @@ public void StoreExport(string userId, string filePath)
/// <returns> Path to the Lift file on disk. </returns>
public string? RetrieveExport(string userId)
{
if (!_liftExports.ContainsKey(userId) || _liftExports[userId] == InProgress)
{
return null;
}

return _liftExports[userId];
_liftExports.TryGetValue(userId, out var exportPath);
return exportPath == InProgress ? null : exportPath;
}

/// <summary> Delete a stored Lift export path and its file on disk. </summary>
Expand All @@ -194,12 +187,8 @@ public void StoreImport(string userId, string filePath)
/// <returns> Path to the Lift file on disk. </returns>
public string? RetrieveImport(string userId)
{
if (!_liftImports.ContainsKey(userId))
{
return null;
}

return _liftImports[userId];
_liftImports.TryGetValue(userId, out var importPath);
return importPath;
}

/// <summary> Delete a stored Lift import path and its file on disk. </summary>
Expand Down Expand Up @@ -499,11 +488,11 @@ private static void AddSenses(LexEntry entry, Word wordEntry, Dictionary<string,
var defDict = new Dictionary<string, string>();
foreach (var def in currentSense.Definitions)
{
if (defDict.ContainsKey(def.Language))
if (defDict.TryGetValue(def.Language, out var defText))
{
// This is an unexpected situation but rather than crashing or losing data we
// will just append extra definitions for the language with a separator.
defDict[def.Language] = $"{defDict[def.Language]}{sep}{def.Text}";
defDict[def.Language] = $"{defText}{sep}{def.Text}";
}
else
{
Expand All @@ -513,11 +502,11 @@ private static void AddSenses(LexEntry entry, Word wordEntry, Dictionary<string,
var glossDict = new Dictionary<string, string>();
foreach (var gloss in currentSense.Glosses)
{
if (glossDict.ContainsKey(gloss.Language))
if (glossDict.TryGetValue(gloss.Language, out var glossDef))
{
// This is an unexpected situation but rather than crashing or losing data we
// will just append extra definitions for the language with a separator.
glossDict[gloss.Language] = $"{glossDict[gloss.Language]}{sep}{gloss.Def}";
glossDict[gloss.Language] = $"{glossDef}{sep}{gloss.Def}";
}
else
{
Expand Down
48 changes: 18 additions & 30 deletions Backend/Services/StatisticsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,28 +91,23 @@ public async Task<List<WordsPerDayPerUserCount>> GetWordsPerDayPerUserCounts(str
{
var dateKey = ParseDateTimePermissivelyWithException(sd.Created)
.ToISO8601TimeFormatDateOnlyString();
if (!shortTimeDictionary.ContainsKey(dateKey))
if (!shortTimeDictionary.TryGetValue(dateKey, out var chartNode))
{
var tempBarChartNode = new WordsPerDayPerUserCount(sd.Created);
foreach (User u in projectUsers)
chartNode = new WordsPerDayPerUserCount(sd.Created);
foreach (var u in projectUsers)
{
tempBarChartNode.UserNameCountDictionary.Add(u.Username, 0);
chartNode.UserNameCountDictionary.Add(u.Username, 0);
}
shortTimeDictionary.Add(dateKey, tempBarChartNode);
shortTimeDictionary.Add(dateKey, chartNode);
}

var chartNode = shortTimeDictionary[dateKey];
var username = userNameIdDictionary.GetValueOrDefault(sd.UserId, "?");
// A semantic domain shouldn't usually have `.Created` without a valid `.UserId`;
// this case is a safe-guard to allow a project owner to see statistics even if there's an
// error in the user reckoning (e.g., if a user is removed from the project mid-workshop).
if (!chartNode.UserNameCountDictionary.ContainsKey(username))
if (!chartNode.UserNameCountDictionary.TryAdd(username, 1))
{
chartNode.UserNameCountDictionary.Add(username, 1);
}
else
{
chartNode.UserNameCountDictionary[username] += 1;
chartNode.UserNameCountDictionary[username]++;
}
}
}
Expand Down Expand Up @@ -163,14 +158,10 @@ public async Task<ChartRootData> GetProgressEstimationLineChartRoot(string proje
{
continue;
}
else if (totalCountDictionary.ContainsKey(dateString))
else if (!totalCountDictionary.TryAdd(dateString, 1))
{
totalCountDictionary[dateString]++;
}
else
{
totalCountDictionary.Add(dateString, 1);
}
}
}
}
Expand Down Expand Up @@ -211,12 +202,11 @@ public async Task<ChartRootData> GetProgressEstimationLineChartRoot(string proje
{
LineChartData.Dates.Add(workshopSchedule[i]);
var day = workshopSchedule[i];
totalCountDictionary.TryGetValue(day, out today);
if (LineChartData.Datasets.Count == 0)
{
runningTotal = totalCountDictionary.ContainsKey(day) ? totalCountDictionary[day] : 0;
today = yesterday = runningTotal;
LineChartData.Datasets.Add(new Dataset(
"Daily Total", (totalCountDictionary.ContainsKey(day) ? totalCountDictionary[day] : 0)));
runningTotal = yesterday = today;
LineChartData.Datasets.Add(new Dataset("Daily Total", today));
LineChartData.Datasets.Add(new Dataset("Average", averageValue));
LineChartData.Datasets.Add(new Dataset("Running Total", runningTotal));
LineChartData.Datasets.Add(new Dataset("Projection", projection));
Expand All @@ -227,7 +217,6 @@ public async Task<ChartRootData> GetProgressEstimationLineChartRoot(string proje
// not generate data after the current date for "Daily Total", "Average" and "Running Total"
if (ParseDateTimePermissivelyWithException(day).CompareTo(DateTime.Now) <= 0)
{
today = totalCountDictionary.ContainsKey(day) ? totalCountDictionary[day] : 0;
runningTotal += today;
LineChartData.Datasets.Find(element => element.UserName == "Daily Total")?.Data.Add(today);
LineChartData.Datasets.Find(element => element.UserName == "Average")?.Data.Add(averageValue);
Expand Down Expand Up @@ -332,18 +321,17 @@ public async Task<List<SemanticDomainUserCount>> GetSemanticDomainUserCounts(str
{
var userId = sd.UserId;
var domainName = sd.Name;
var domainUserValue = new SemanticDomainUserCount();

// if the SemanticDomain have a userId and exist in HashMap
domainUserValue = (userId is not null && resUserMap.ContainsKey(userId)
// if true, new SemanticDomain model
? domainUserValue = resUserMap[userId]
// if false, assign to unknownUser
: domainUserValue = resUserMap[unknownId]);
SemanticDomainUserCount? domainUserValue;
if (userId is null || !resUserMap.TryGetValue(userId, out domainUserValue))
{
domainUserValue = resUserMap[unknownId];
}

// update DomainCount
if (!domainUserValue.DomainSet.Contains(domainName))
if (domainUserValue.DomainSet.Add(domainName))
{
domainUserValue.DomainSet.Add(domainName);
domainUserValue.DomainCount++;
}
// update WordCount
Expand Down

0 comments on commit 6302b3c

Please sign in to comment.