Created
May 30, 2022 12:03
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @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