Skip to content

Commit

Permalink
fix: Return partial match when comparing null and zero values for num…
Browse files Browse the repository at this point in the history
…erics if partial matching is enabled
  • Loading branch information
Rickard Bergeling committed Nov 20, 2023
1 parent 083c8eb commit 7b75ddc
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
10 changes: 10 additions & 0 deletions src/comparators.spec.ts
Expand Up @@ -24,6 +24,16 @@ describe('compareNumerics', () => {
compareNumerics(1, 1.01, { allowPartialMatch: true, leeway: Math.abs(1 - 1 / 1.01) })
).toEqual(MatchKey.PARTIAL)
})

it('should partial match null and zero values when partial matching is enabled', () => {
expect(compareNumerics(0, null, { allowPartialMatch: true })).toEqual(MatchKey.PARTIAL)
expect(compareNumerics(null, 0, { allowPartialMatch: true })).toEqual(MatchKey.PARTIAL)
})

it('should not partial match null and zero values when partial matching is disabled', () => {
expect(compareNumerics(0, null, { allowPartialMatch: false })).toEqual(MatchKey.NO)
expect(compareNumerics(null, 0, { allowPartialMatch: false })).toEqual(MatchKey.NO)
})
})

describe('fullOrNoMatchComparison', () => {
Expand Down
7 changes: 5 additions & 2 deletions src/comparators.ts
Expand Up @@ -30,12 +30,15 @@ export const fullOrNoMatchComparison: ComparisonFn = (parsed, labeled) => {
}

export const compareNumerics: ComparisonFn<number | null> = (parsed, labeled, options) => {
const { allowPartialMatch = false, leeway } = options || {}
if (parsed === null && labeled === null) return null
if (parsed === 0 && labeled === null && allowPartialMatch) return MatchKey.PARTIAL
if (parsed === null && labeled === 0 && allowPartialMatch) return MatchKey.PARTIAL
if (parsed === null || labeled === null) return MatchKey.NO

const match = fullOrNoMatchComparison(parsed, labeled)
if (match === MatchKey.NO && options?.allowPartialMatch && options?.leeway) {
const { upper, lower } = getUpperLowerLeewayBounds(labeled, options.leeway)
if (match === MatchKey.NO && allowPartialMatch && leeway) {
const { upper, lower } = getUpperLowerLeewayBounds(labeled, leeway)
const withinRange = parsed >= lower && parsed <= upper
if (withinRange) {
return MatchKey.PARTIAL
Expand Down

0 comments on commit 7b75ddc

Please sign in to comment.