Created
June 2, 2017 22:14
-
-
Save BenAychh/ca5b23eeb45fdf76271099e09808f240 to your computer and use it in GitHub Desktop.
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
const R = require('ramda'); | |
/** | |
* wanted a functional way to do this that did not modify the params | |
**/ | |
function deepReplaceInObject(currentValue, newValue, objectToReplaceIn) { | |
const paramType = R.type(objectToReplaceIn); | |
if (paramType === 'Object') { | |
return R.keys(objectToReplaceIn).reduce((object, key) => { | |
const type = R.type(objectToReplaceIn[key]); | |
if (type === 'Object' || type === 'Array') { | |
return R.merge(object, { | |
[key]: deepReplaceInObject(currentValue, newValue, objectToReplaceIn[key]), | |
}); | |
} else if (objectToReplaceIn[key] === currentValue) { | |
return R.merge(object, { [key]: newValue }); | |
} | |
return R.merge(object, { [key]: objectToReplaceIn[key] }); | |
}, {}); | |
} else if (paramType === 'Array') { | |
return objectToReplaceIn.reduce((array, value) => { | |
const type = R.type(value); | |
if (type === 'Object' || type === 'Array') { | |
return [...array, deepReplaceInObject(currentValue, newValue, value)]; | |
} else if (value === currentValue) { | |
return [...array, newValue]; | |
} | |
return [...array, value]; | |
}, []); | |
} | |
return objectToReplaceIn; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment