Skip to content

Instantly share code, notes, and snippets.

@Restuta
Last active August 30, 2017 01:06
Show Gist options
  • Save Restuta/d4fb8e4bdbfa27939c38827c5687b84f to your computer and use it in GitHub Desktop.
Save Restuta/d4fb8e4bdbfa27939c38827c5687b84f to your computer and use it in GitHub Desktop.
mapValuesDeep with circular references detection
// based on vanilla lodash, todo: rewrite with lodash/fp
// uses isPlainObject to detect ojbects to go deep into
// detects circular references using Set()
function mapValuesDeep(originalObj, mapFunc) {
const visitedObjects = new Set()
const mapValues = (originalObj, mapFunc) =>
_.mapValues(originalObj, value => {
if (_.isPlainObject(value)) {
// detecting circular references
if (visitedObjects.has(value)) {
return value
}
visitedObjects.add(value)
return mapValues(value, mapFunc)
}
return mapFunc(value)
})
return mapValues(originalObj, mapFunc)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment