Skip to content

Refactor code to be more clear to read #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 17, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@

import com.teamtreehouse.flashy.domain.FlashCard;
import com.teamtreehouse.flashy.repositories.FlashCardRepository;

import org.hibernate.mapping.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import static java.util.stream.Collectors.toList;

Expand Down Expand Up @@ -52,21 +52,20 @@ public FlashCard getNextUnseenFlashCard(Collection<Long> seenIds) {
@Override
public FlashCard getNextFlashCardBasedOnViews(Map<Long, Long> idToViewCounts) {
FlashCard card = getNextUnseenFlashCard(idToViewCounts.keySet());
if (card != null) {
return card;
if (card == null) {
card = getLeastViewedFlashCard(idToViewCounts);
}
return card;
}

public FlashCard getLeastViewedFlashCard(Map<Long, Long> idToViewCounts) {
Long leastViewedId = null;
for (Map.Entry<Long, Long> entry : idToViewCounts.entrySet()) {
if (leastViewedId == null) {
leastViewedId = entry.getKey();
continue;
}
Long lowestScore = idToViewCounts.get(leastViewedId);
if (entry.getValue() < lowestScore) {
leastViewedId = entry.getKey();
}
}
return flashCardRepository.findOne(leastViewedId);
List<Map.Entry<Long, Long>> entries = new ArrayList<>(idToViewCounts.entrySet());
Collections.shuffle(entries);
return entries.stream()
.min(Comparator.comparing(Map.Entry::getValue))
.map(entry -> flashCardRepository.findOne(entry.getKey()))
.orElseThrow(IllegalArgumentException::new);
}

@Override
Expand Down