Skip to content

Commit

Permalink
fix(internal): add deepEqual functionality for comparing two objects (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
TarikGul authored Feb 6, 2024
1 parent 46a4d07 commit e305138
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 4 deletions.
6 changes: 2 additions & 4 deletions src/AssetTransferApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ import {
UnsignedTransaction,
XcmDirection,
} from './types';
import { deepEqual } from './util/deepEqual';
import { resolveMultiLocation } from './util/resolveMultiLocation';
import { sanitizeKeys } from './util/sanitizeKeys';
import { validateNumber } from './validate';
Expand Down Expand Up @@ -845,10 +846,7 @@ export class AssetTransferApi {
const firstLpToken = sanitizeKeys(JSON.parse(firstLpTokenSlice)) as UnionXcmMultiLocation;
const secondLpToken = sanitizeKeys(JSON.parse(secondLpTokenSlice)) as UnionXcmMultiLocation;

if (
JSON.stringify(firstLpToken) == JSON.stringify(feeAsset) ||
JSON.stringify(secondLpToken) == JSON.stringify(feeAsset)
) {
if (deepEqual(firstLpToken, feeAsset) || deepEqual(secondLpToken, feeAsset)) {
return [true, feeAsset];
}
}
Expand Down
14 changes: 14 additions & 0 deletions src/util/deepEqual.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { deepEqual } from './deepEqual';

describe('deepEqual', () => {
it('Should return true for 2 equal objects that are out of order', () => {
const a = { x: { y: 'z' }, z: ['1', '2', '3'] };
const b = { z: ['1', '2', '3'], x: { y: 'z' } };
expect(deepEqual(a, b)).toEqual(true);
});
it('Should return false with 2 unequal objects', () => {
const a = { x: { y: 'z' }, z: ['1', '2', '3'] };
const b = { w: { y: 'z' }, z: ['1', '2', '3'] };
expect(deepEqual(a, b)).toEqual(false);
});
});
19 changes: 19 additions & 0 deletions src/util/deepEqual.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { AnyJson } from '@polkadot/types/types';
/* eslint-disable @typescript-eslint/no-unsafe-argument */

/**
* Courtesy of https://stackoverflow.com/a/32922084/13609948 for this solution.
* Checks the equality between 2 objects.
*
* @param x
* @param y
* @returns
*/
export function deepEqual(x: AnyJson, y: AnyJson): boolean {
const ok = Object.keys,
tx = typeof x,
ty = typeof y;
return x && y && tx === 'object' && tx === ty
? ok(x).length === ok(y).length && ok(x).every((key) => deepEqual(x[key], y[key]))
: x === y;
}

0 comments on commit e305138

Please sign in to comment.