Skip to content

Instantly share code, notes, and snippets.

@JavierCane
Created April 18, 2017 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JavierCane/1b70f6572277e5795fe0badee8759d64 to your computer and use it in GitHub Desktop.
Save JavierCane/1b70f6572277e5795fe0badee8759d64 to your computer and use it in GitHub Desktop.
Functional approach for the Finder Refactoring Kata. More info: http://codely.tv/screencasts/finder-kata-scala/
// Post: http://codely.tv/screencasts/finder-kata-scala/
// Repo: https://github.com/CodelyTV/incomprehensible-finder-refactoring-kata-scala
package tv.codely.finderKata.algorithm
final class BestPeoplePairFinder() {
def find(people: Seq[Person], peoplePairCriterion: Ordering[PeoplePair]): Option[PeoplePair] = {
val canFindPeoplePairs = people.size >= 2
if (!canFindPeoplePairs) {
None
} else {
val peoplePairs = people.combinations(PeoplePair.numberOfPeopleInAPair).map { peopleCombination =>
val sortedPeopleCombination = peopleCombination.sorted
PeoplePair(sortedPeopleCombination.head, sortedPeopleCombination(1))
}
val bestPeoplePair = peoplePairs.reduce { (bestPeoplePair, candidatePeoplePair) =>
val isBetterCandidate = peoplePairCriterion.compare(bestPeoplePair, candidatePeoplePair) < 0
if (isBetterCandidate) candidatePeoplePair else bestPeoplePair
}
Some(bestPeoplePair)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment