Skip to content
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

Boost if exact match #2

Open
AJamesPhillips opened this issue Jun 1, 2020 · 0 comments
Open

Boost if exact match #2

AJamesPhillips opened this issue Jun 1, 2020 · 0 comments

Comments

@AJamesPhillips
Copy link

AJamesPhillips commented Jun 1, 2020

Thank you very much for the code based on the Sørensen–Dice coefficient.

I made a minor addition to increase the score when there's an exact match at the start, or part way through. This is 10 minutes work so lacks any of the consideration you've put into the existing code. I'm also sure there must be many additional well considered and published improvements. I'm sharing this variant in case someone else finds it adds value to their application.

Thank you again!
AJP

export const stringSimilarity = (str1: string, str2: string, substringLength: number = 2, caseSensitive: boolean = false) => {
	if (!caseSensitive) {
		str1 = str1.toLowerCase()
		str2 = str2.toLowerCase()
	}

	if (str1.length < substringLength || str2.length < substringLength) return 0

	let boost = 1
	if (str1.startsWith(str2) || str2.startsWith(str1)) boost = 4
	else if (str1.includes(str2) || str2.includes(str1)) boost = 2

	const map = new Map()
	for (let i = 0; i < str1.length - (substringLength - 1); i++) {
		const substr1 = str1.substr(i, substringLength)
		map.set(substr1, map.has(substr1) ? map.get(substr1) + 1 : 1)
	}

	let match = 0
	for (let j = 0; j < str2.length - (substringLength - 1); j++) {
		const substr2 = str2.substr(j, substringLength)
		const count = map.has(substr2) ? map.get(substr2) : 0
		if (count > 0) {
			map.set(substr2, count - 1)
			match++
		}
	}

	const score = (match * 2) / (str1.length + str2.length - ((substringLength - 1) * 2))

	return Math.min(1, score * boost)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant