Skip to content

Instantly share code, notes, and snippets.

@r-k-b
Last active May 22, 2016 05:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save r-k-b/12dfe5375543c91c28c1661eb98285a8 to your computer and use it in GitHub Desktop.
Save r-k-b/12dfe5375543c91c28c1661eb98285a8 to your computer and use it in GitHub Desktop.
a little closer to understanding Transducers and Transformers...
"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