Skip to content

Commit

Permalink
ignore undefined in objects for comparison
Browse files Browse the repository at this point in the history
Signed-off-by: Berend Sliedrecht <[email protected]>
  • Loading branch information
berendsliedrecht committed Nov 2, 2023
1 parent c0254d5 commit f3a3992
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 4 deletions.
7 changes: 5 additions & 2 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,11 @@ export const simpleDeepEqual = (lhs: unknown, rhs: unknown): boolean => {

if (typeof lhs !== 'object' || typeof rhs !== 'object') return false

const l = lhs as Record<string, unknown>
const r = rhs as Record<string, unknown>
const l = { ...lhs } as Record<string, unknown>
const r = { ...rhs } as Record<string, unknown>

Object.keys(l).forEach((key) => l[key] === undefined && delete l[key])
Object.keys(r).forEach((key) => l[key] === undefined && delete l[key])

const keys1 = Object.keys(l)
const keys2 = Object.keys(r)
Expand Down
51 changes: 49 additions & 2 deletions tests/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { before, describe, it } from 'node:test'
import { deepStrictEqual } from 'node:assert'
import assert, { deepStrictEqual } from 'node:assert'

import { deleteByPath, getAllKeys } from '../src/utils'
import { deleteByPath, getAllKeys, simpleDeepEqual } from '../src/utils'

import { prelude } from './utils'

Expand Down Expand Up @@ -61,6 +61,53 @@ describe('utils', () => {
)
})

describe('simple deep equality', () => {
it('simple object comparison', () => {
const l = {
a: 'b',
c: 'd'
}

const r = {
a: 'b',
c: 'd'
}

assert(simpleDeepEqual(l, r))
})

it('simple object ignore undefined comparison', () => {
const l = {
a: 'b',
c: 'd',
d: undefined
}

const r = {
a: 'b',
c: 'd'
}

assert(simpleDeepEqual(l, r))
})

it('simple string comparison', () => {
const l = 'a'

const r = 'a'

assert(simpleDeepEqual(l, r))
})

it('simple number comparison', () => {
const l = 1

const r = 1

assert(simpleDeepEqual(l, r))
})
})

describe('get all keys', () => {
it('get all non-nested keys', () => {
const obj = {
Expand Down

0 comments on commit f3a3992

Please sign in to comment.