Skip to content

Instantly share code, notes, and snippets.

@employee451
Created May 30, 2022 12:03
Show Gist options
  • Save employee451/bfba22590864a74a652a1c3ea4dec8a5 to your computer and use it in GitHub Desktop.
Save employee451/bfba22590864a74a652a1c3ea4dec8a5 to your computer and use it in GitHub Desktop.
// @see https://gist.github.com/employee451/938ae007cddd9733b64acb9a958428bd
import { getNestedObjectKeyNames } from '@shared/helpers/getNestedObjectKeyNames'
type MissingKeyResult = {
/** The index of the object that has the missing key */
missingKeyObject: number
/** The index of the object where the missing key comes from */
missingKeyOrigin: number
/** Name of the key that is missing */
keyName: string
}
/**
* Finds missing keys between any number of objects. If one of the objects has a key that is missing in one or more of the other objects,
* all instances where it is missing will be added to the missing key result.
* @param objects
*/
export const findMissingKeys = (
...objects: Record<string, any>[]
): MissingKeyResult[] => {
if (objects.length === 0) {
return []
}
const missingKeys: MissingKeyResult[] = []
const addMissingKey = (key: MissingKeyResult) => {
// Prevent duplicate results
if (
!missingKeys.some(
({ missingKeyObject, missingKeyOrigin, keyName }) =>
missingKeyObject === key.missingKeyObject &&
missingKeyOrigin === key.missingKeyOrigin &&
keyName === key.keyName
)
) {
missingKeys.push(key)
}
}
// Loop through each object and compare the keys of all other objects to this one
objects.forEach((currentObject, currentObjectIndex) => {
const keyNames = getNestedObjectKeyNames(currentObject)
// Go through each object and check that it has every key
objects.forEach((object, index) => {
const nestedKeys = getNestedObjectKeyNames(object)
const missingKeys = keyNames.filter((key) => !nestedKeys.includes(key))
missingKeys.forEach((key) =>
addMissingKey({
missingKeyObject: index,
missingKeyOrigin: currentObjectIndex,
keyName: key,
})
)
})
})
return missingKeys
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment