Skip to content

Instantly share code, notes, and snippets.

@wallace-sf
Last active May 4, 2022 20:45
Show Gist options
  • Select an option

  • Save wallace-sf/c221e23c1b655113fc1170547d7e5286 to your computer and use it in GitHub Desktop.

Select an option

Save wallace-sf/c221e23c1b655113fc1170547d7e5286 to your computer and use it in GitHub Desktop.
Check if field name is in a cyclic object map
/**
* @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);
});
};
@wallace-sf

wallace-sf commented Feb 11, 2022

Copy link
Copy Markdown
Author

line 33, get function is from lodash

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment