summaryrefslogtreecommitdiff
path: root/core/source/main/scala/com/rockymadden/stringmetric/phonetic/SoundexMetric.scala
blob: e4daa177e8aca6b2a8ba13fb9ef87e0297ca583c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.rockymadden.stringmetric.phonetic

import com.rockymadden.stringmetric.{StringFilter, StringMetric}
import com.rockymadden.stringmetric.Alphabet.Alpha

/** An implementation of the Soundex metric. */
class SoundexMetric extends StringMetric[DummyImplicit, Boolean] { this: StringFilter =>
	final override def compare(charArray1: Array[Char], charArray2: Array[Char])
		(implicit di: DummyImplicit): Option[Boolean] = {

		val fca1 = filter(charArray1)
		lazy val fca2 = filter(charArray2)

		if (fca1.length == 0 || !(Alpha isSuperset fca1.head) || fca2.length == 0 || !(Alpha isSuperset fca2.head)) None
		else if (fca1.head.toLower != fca2.head.toLower) Some(false)
		else SoundexAlgorithm.compute(fca1).filter(_.length > 0).flatMap(se1 =>
			SoundexAlgorithm.compute(fca2).filter(_.length > 0).map(se1.sameElements(_))
		)
	}

	final override def compare(string1: String, string2: String)(implicit di: DummyImplicit): Option[Boolean] =
		compare(string1.toCharArray, string2.toCharArray)
}

object SoundexMetric {
	private lazy val self = apply()

	def apply(): SoundexMetric = new SoundexMetric with StringFilter

	def compare(charArray1: Array[Char], charArray2: Array[Char]) = self.compare(charArray1, charArray2)

	def compare(string1: String, string2: String) = self.compare(string1, string2)
}