Last active
May 4, 2022 20:45
-
-
Save wallace-sf/c221e23c1b655113fc1170547d7e5286 to your computer and use it in GitHub Desktop.
Check if field name is in a cyclic object map
This file contains hidden or 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
/** | |
* @description check if field name is in a cyclic object map | |
* @author Wallace Ferreira <https://github.com/wallace-sf> | |
* @example | |
* ```js | |
* var mapA = { | |
* a: ['b', 'c', 'd', 'e'], | |
* b: ['c', 'd'], | |
* c: ['d'], | |
* d: ['f', 'a'], | |
* } | |
* | |
* var mapB = { | |
* a: ['b', 'c', 'd', 'e'], | |
* b: ['c', 'd'], | |
* c: ['d'], | |
* d: ['f', 'k'], | |
* } | |
* | |
* isCyclic('b', mapA); | |
* => true | |
* | |
* isCyclic('b', mapB); | |
*=> false | |
* ``` | |
* @param {string} fieldName | |
* @param {object} ObjectMap | |
* @param {string[]} mapKeys | |
* @returns {boolean} | |
*/ | |
const isCyclic = (fieldName = '', objectMap = {}, mapKeys = []) => { | |
const currentMapKeys = [...mapKeys]; | |
const currentMapValue = get(objectMap, fieldName, []); | |
if (currentMapKeys.includes(fieldName)) return true; | |
currentMapKeys.push(fieldName); | |
return currentMapValue.some((currentKey) => { | |
return isCyclic(currentKey, objectMap, currentMapKeys); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
line 33, get function is from lodash