Files
SnowLuma/.pnpm-store/v11/files/e9/defbe2ed10802a61c9fb36705296b41d87dedac6c257334e75db1c0805a9bd8ccb9dd0de42cbaf918b88e537a9a0d567360cc3dfb634e8238e7ed5ad6aa6f0
T
TanTan 2a69b23b47
Dev Build / cleanup (push) Waiting to run
Dev Build / typecheck (push) Waiting to run
docs: 仓库链接指向本镜像仓库
2026-11-13 09:27:07 +08:00

52 lines
1.5 KiB
Plaintext

import { distance } from 'fastest-levenshtein'
import { RankedDictionary } from '../types'
const getUsedThreshold = (
password: string,
entry: string,
threshold: number,
) => {
const isPasswordToShort = password.length <= entry.length
const isThresholdLongerThanPassword = password.length <= threshold
const shouldUsePasswordLength =
isPasswordToShort || isThresholdLongerThanPassword
// if password is too small use the password length divided by 4 while the threshold needs to be at least 1
return shouldUsePasswordLength ? Math.ceil(password.length / 4) : threshold
}
export interface FindLevenshteinDistanceResult {
levenshteinDistance: number
levenshteinDistanceEntry: string
}
const findLevenshteinDistance = (
password: string,
rankedDictionary: RankedDictionary,
threshold: number,
): Partial<FindLevenshteinDistanceResult> => {
let foundDistance = 0
const found = Object.keys(rankedDictionary).find((entry) => {
const usedThreshold = getUsedThreshold(password, entry, threshold)
if (Math.abs(password.length - entry.length) > usedThreshold) {
return false
}
const foundEntryDistance = distance(password, entry)
const isInThreshold = foundEntryDistance <= usedThreshold
if (isInThreshold) {
foundDistance = foundEntryDistance
}
return isInThreshold
})
if (found) {
return {
levenshteinDistance: foundDistance,
levenshteinDistanceEntry: found,
}
}
return {}
}
export default findLevenshteinDistance