Last active
January 31, 2021 11:42
-
-
Save guangtuan/06bd3ed45345285547411193a5ca8551 to your computer and use it in GitHub Desktop.
demo of ramda usage
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
| const { | |
| compose, | |
| not, | |
| prop, | |
| ifElse, | |
| map, | |
| flip, | |
| zipObj, | |
| chain, | |
| zipWith, | |
| assoc | |
| } = require('ramda'); | |
| const input = { | |
| result: [ | |
| { blockId: 1, }, | |
| { blockId: 2, }, | |
| ], | |
| blocks: [ | |
| { id: 1, pid: 2, }, | |
| { id: 2, pid: 3, }, | |
| { id: 3, pid: 4, }, | |
| { id: 4, pid: null, } | |
| ] | |
| }; | |
| const expected = [ | |
| { id: 1, top: 4 }, | |
| { id: 2, top: 4 } | |
| ]; | |
| const debug = tag => any => { | |
| console.log(tag, JSON.stringify(any, null, 4)); | |
| return any; | |
| }; | |
| const propFrom = object => property => object[property]; | |
| const f = lookup => ifElse( | |
| compose(not, prop('pid'), propFrom(lookup), prop('id')), | |
| prop('id'), | |
| compose( | |
| _ => f(lookup)(_), | |
| propFrom(lookup), | |
| prop('pid'), | |
| ) | |
| ); | |
| const transform = ({ result, blocks }) => { | |
| const lookup = chain(zipObj, (map(prop('id'))))(blocks); | |
| return chain( | |
| zipWith(assoc('top')), | |
| map(compose(f(lookup), propFrom(lookup), prop('blockId'))) | |
| )(result); | |
| }; | |
| debug('result:')(transform(input)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment