Skip to content

Commit

Permalink
feat: add isEqual
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Aug 4, 2022
1 parent 564e80b commit 098b1ec
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 2 deletions.
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,19 @@ import { objectHash } from 'ohash'
console.log(objectHash({ foo: 'bar'}))
```

### `isEqual(obj1, obj2, options?)`

Compare two objects using reference equality and stable object hashing.

Usage:

```js
import { isEqual } from 'ohash'

// true
console.log(isEqual({ a: 1, b: 2 }, { b: 2, a: 1 }))
```

### `murmurHash(str)`

Converts input string (of any length) into a 32-bit positive integer using [MurmurHash3]((https://en.wikipedia.org/wiki/MurmurHash)).
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export { objectHash } from './object-hash'
export { hash } from './hash'
export { murmurHash } from './crypto/murmur'
export { sha256 } from './crypto/sha256'
export { isEqual } from './utils'
18 changes: 18 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { objectHash, HashOptions } from './object-hash'
/**
* Compare two objects using reference equality and stable deep hashing.
* @param {any} object1 First object
* @param {any} object2 Second object
* @param {HashOptions} hash options
* @return {boolean} true if equal and false if not
* @api public
*/
export function isEqual (object1: any, object2: any, hashOptions: HashOptions = {}): boolean {
if (object1 === object2) {
return true
}
if (objectHash(object1, hashOptions) === objectHash(object2, hashOptions)) {
return true
}
return false
}
20 changes: 18 additions & 2 deletions test/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expect, it } from 'vitest'
import { murmurHash, objectHash, hash, sha256 } from '../src'
import { describe, expect, it } from 'vitest'
import { murmurHash, objectHash, hash, sha256, isEqual } from '../src'
import { sha256base64 } from '../src/crypto/sha256'

it('murmurHash', () => {
Expand All @@ -23,3 +23,19 @@ it('objectHash', () => {
it('hash', () => {
expect(hash({ foo: 'bar' })).toMatchInlineSnapshot('"dZbtA7f0lK"')
})

describe('isEqual', () => {
const cases = [
[{ foo: 'bar' }, { foo: 'bar' }, true],
[{ foo: 'bar' }, { foo: 'baz' }, false],
[{ a: 1, b: 2 }, { b: 2, a: 1 }, true],
[123, 123, true],
[123, 456, false],
[[1, 2], [2, 1], false]
]
for (const [obj1, obj2, equals] of cases) {
it(`${JSON.stringify(obj1)} ${equals ? 'equals' : 'not equals'} to ${JSON.stringify(obj2)}`, () => {
expect(isEqual(obj1, obj2)).toBe(equals)
})
}
})

0 comments on commit 098b1ec

Please sign in to comment.