as-services/libs/utils/words-id/autocorrect/BKNodeLetters.js
devthejo 16b7e7d6aa
All checks were successful
/ build (map[dockerfile:./services/hasura/Dockerfile name:hasura]) (push) Successful in 47s
/ build (map[dockerfile:./services/web/Dockerfile name:web]) (push) Successful in 1m47s
/ build (map[dockerfile:./services/watchers/Dockerfile name:watchers]) (push) Successful in 2m37s
/ build (map[dockerfile:./services/files/Dockerfile name:files]) (push) Successful in 2m52s
/ build (map[dockerfile:./services/api/Dockerfile name:api]) (push) Successful in 3m2s
/ build (map[dockerfile:./services/app/Dockerfile name:app]) (push) Successful in 31s
/ build (map[dockerfile:./services/tasks/Dockerfile name:tasks]) (push) Successful in 2m44s
/ deploy (push) Successful in 48s
chore(init): available sources
2025-04-13 10:46:53 +02:00

49 lines
1.2 KiB
JavaScript

const levenshtein = require("fast-levenshtein")
module.exports = class BKNodeLetters {
constructor(word) {
this.word = word
this.children = new Map()
}
insert(otherWord) {
const dist = levenshtein.get(this.word, otherWord)
if (this.children.has(dist)) {
this.children.get(dist).insert(otherWord)
} else {
this.children.set(dist, new BKNodeLetters(otherWord))
}
}
search(target, maxDist) {
const currentDist = levenshtein.get(this.word, target)
// If the distance is within the acceptable maximum, return this word immediately
if (currentDist <= maxDist) {
return { word: this.word, distance: currentDist }
}
let minDistanceWord = null
for (
let i = Math.max(0, currentDist - maxDist);
i <= currentDist + maxDist;
i++
) {
if (this.children.has(i)) {
const result = this.children.get(i).search(target, maxDist)
if (
result &&
(!minDistanceWord || result.distance < minDistanceWord.distance)
) {
minDistanceWord = result
if (result.distance <= 1) {
// Early stop if very close match found
break
}
}
}
}
return minDistanceWord
}
}