Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions packages/cli-kit/src/public/common/object.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
compact,
deepCompare,
deepCompareWithOrderInsensitiveArrays,
deepDifference,
deepMergeObjects,
getPathValue,
Expand Down Expand Up @@ -116,6 +117,40 @@ describe('deepCompare', () => {
})
})

describe('deepCompareWithOrderInsensitiveArrays', () => {
test('returns true when arrays contain the same values in a different order', () => {
const first = {
webhooks: {
subscriptions: [
{topic: 'orders/delete', uri: 'https://example.com/orders/delete'},
{topic: 'products/update', uri: 'https://example.com/products/update'},
],
},
}
const second = {
webhooks: {
subscriptions: [
{uri: 'https://example.com/products/update', topic: 'products/update'},
{uri: 'https://example.com/orders/delete', topic: 'orders/delete'},
],
},
}

const result = deepCompareWithOrderInsensitiveArrays(first, second)

expect(result).toBeTruthy()
})

test('returns false when arrays contain different values', () => {
const first = {items: [{id: 1}, {id: 2}]}
const second = {items: [{id: 1}, {id: 3}]}

const result = deepCompareWithOrderInsensitiveArrays(first, second)

expect(result).toBeFalsy()
})
})

describe('deepDifference', () => {
test('returns the difference between two objects', () => {
// Given
Expand Down
31 changes: 31 additions & 0 deletions packages/cli-kit/src/public/common/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,37 @@ export function deepCompare(one: object, two: object): boolean {
return lodashIsEqual(one, two)
}

/**
* Deeply compares two values and treats arrays as order-insensitive.
*
* @param one - The first value to be compared.
* @param two - The second value to be compared.
* @returns True if the normalized values are equal, false otherwise.
*/
export function deepCompareWithOrderInsensitiveArrays(one: unknown, two: unknown): boolean {
return lodashIsEqual(normalizeOrderInsensitiveArrays(one), normalizeOrderInsensitiveArrays(two))
}

function normalizeOrderInsensitiveArrays(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map(normalizeOrderInsensitiveArrays).sort(compareNormalizedValues)
}

if (value && typeof value === 'object') {
return Object.fromEntries(
Object.entries(value)
.sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey))
.map(([key, nestedValue]) => [key, normalizeOrderInsensitiveArrays(nestedValue)]),
)
}

return value ?? {}
}

function compareNormalizedValues(left: unknown, right: unknown) {
return JSON.stringify(left).localeCompare(JSON.stringify(right))
}

/**
* Return the difference between two nested objects.
*
Expand Down
Loading