Forked from busypeoples/TransformingDeeplyNestedData.js
Created
August 15, 2017 17:51
-
-
Save srdjan/5fc740d65d65b954534480c0d52446d2 to your computer and use it in GitHub Desktop.
Transforming Deeply Nested Data
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
import { | |
always, | |
equals, | |
identity, | |
ifElse, | |
map, | |
partial, | |
} from 'ramda' | |
const isObject = input => input !== null && typeof input === 'object' | |
/** | |
* Like map but for deeply nested objects | |
* | |
* @param {Function} f function to apply | |
* @param {Object} obj | |
*/ | |
const nestedMap = (f, obj) => map(ifElse(isObject, partial(nestedMap, [f]), f), obj) | |
// verify | |
nestedMap(x => x + 5, [1, [[[2]]]]) | |
// [ | |
// 6, | |
// [ | |
// [ | |
// [ | |
// 7 | |
// ] | |
// ] | |
// ] | |
// ] | |
nestedMap(x => x + 5, {a: 1, b: { c: { d: 2 }}}) | |
// {"a":6,"b":{"c":{"d":7}}} | |
const inputData = { a: 1, b: { c: { d: 2 } }, e: null, f: 3 } | |
const outputData = { a: 1, b: { c: { d: 2 } }, e: '', f: 3 } | |
const transformFrom = data => nestedMap(ifElse(equals(null), always(''), identity), data) | |
const transformTo = data => nestedMap(ifElse(equals(''), always(null), identity), data) | |
console.log(equals(transformTo(transformFrom(inputData)), inputData)) | |
console.log(equals(transformFrom(transformTo(outputData)), outputData)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment