Last active
May 22, 2016 05:54
-
-
Save r-k-b/12dfe5375543c91c28c1661eb98285a8 to your computer and use it in GitHub Desktop.
a little closer to understanding Transducers and Transformers...
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
"use strict"; | |
import R from 'ramda'; | |
let userDays = [ | |
{ | |
days: { | |
day1: { | |
billable: { | |
1: 10, | |
2: 20, | |
}, | |
unbillable: { | |
1: 20, | |
3: 30, | |
}, | |
}, | |
day2: { | |
billable: { | |
1: 30, | |
4: 40, | |
}, | |
unbillable: { | |
1: 40, | |
5: 50, | |
}, | |
}, | |
}, | |
id: 1 | |
}, | |
{ | |
days: { | |
day1: { | |
billable: { | |
1: 50, | |
6: 60, | |
}, | |
unbillable: { | |
1: 60, | |
7: 70, | |
}, | |
}, | |
day2: { | |
billable: { | |
1: 70, | |
8: 80, | |
}, | |
unbillable: { | |
1: 80, | |
9: 90, | |
}, | |
}, | |
}, | |
id: 2 | |
}, | |
]; | |
let daysLens = R.lens(R.prop('days'), R.assoc('days')); | |
/** | |
* userInfoObj → dayObject → dayObjectWithUserInfo | |
*/ | |
let addUserInfoToDay = userInfo => R.map(R.merge(userInfo)); | |
/** | |
* [userDays] → [userDays] | |
*/ | |
let addUserInfoToDays = R.map(userDay => R.over( | |
daysLens, | |
addUserInfoToDay(R.omit(['days'], userDay)), | |
userDay | |
)); | |
/** | |
* a → b | |
*/ | |
let makeDayKeysUnique = daysObj => R.fromPairs( | |
R.map( | |
pair => [ | |
`${ pair[0]}~${ R.prop('id', pair[1]) }`, | |
pair[1] | |
], | |
R.toPairs(daysObj) | |
) | |
); | |
/** | |
* What's the signature for a transducer? | |
*/ | |
let transducer = R.compose( | |
addUserInfoToDays, | |
R.map(R.over(daysLens, makeDayKeysUnique)) | |
); | |
/** | |
* (acc, val) → acc | |
* | |
* @param acc | |
* @param val | |
* @returns {Observable|*} | |
*/ | |
let transformer = (acc, val) => { | |
return R.merge(acc, R.prop('days', val)); | |
}; | |
let result = R.transduce(transducer, transformer, {}, userDays); | |
console.log('result', JSON.stringify(result, null, 2)); | |
/* | |
result { | |
"day1~1": { | |
"id": 1, | |
"billable": { | |
"1": 10, | |
"2": 20 | |
}, | |
"unbillable": { | |
"1": 20, | |
"3": 30 | |
} | |
}, | |
"day2~1": { | |
"id": 1, | |
"billable": { | |
"1": 30, | |
"4": 40 | |
}, | |
"unbillable": { | |
"1": 40, | |
"5": 50 | |
} | |
}, | |
"day1~2": { | |
"id": 2, | |
"billable": { | |
"1": 50, | |
"6": 60 | |
}, | |
"unbillable": { | |
"1": 60, | |
"7": 70 | |
} | |
}, | |
"day2~2": { | |
"id": 2, | |
"billable": { | |
"1": 70, | |
"8": 80 | |
}, | |
"unbillable": { | |
"1": 80, | |
"9": 90 | |
} | |
} | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment