How to compose two functions together into 1 using FP's compose() javascript?

Viewed 721

How can I compose two functions together into 1 using FP's compose() here's live code: https://repl.it/JXMl/1

I have 3 pure functions:

// groups By some unique key
const groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};

// ungroups the group by
const ungroup = (obj) => {
  return Object.keys(obj)
               .map(x => obj[x]);
};

// flatten array
const flatten = (arrs) => {
  return arrs.reduce((acc, item) => acc.concat(item), [])
}

And a functional utility compose function from Functional Jargon

const compose = (f, g) => (a) => f(g(a))

In the end, I want a ungroupAndFlatten function created through compose().

Along the lines of:

const ungroupAndFlatten = compose(ungroup, flatten) // Usage doesn't work.
console.log(ungroupAndFlatten(obj)) 

Example code:

const arrs = [
  {name: 'abc', effectiveDate: "2016-01-01T00:00:00+00:00"},
  {name: 'abcd', effectiveDate: "2016-02-01T00:00:00+00:00"},
  {name: 'abcd', effectiveDate: "2016-09-01T00:00:00+00:00"},
  {name: 'abc', effectiveDate: "2016-04-01T00:00:00+00:00"},
  {name: 'abc', effectiveDate: "2016-05-01T00:00:00+00:00"},
]; 

const groupedByName = groupBy(arrs, 'name');

// Example Output
//
// var obj = {
//    abc: [
//      { name: 'abc', effectiveDate: '2016-01-01T00:00:00+00:00' },
//      { name: 'abc', effectiveDate: '2016-04-01T00:00:00+00:00' },
//      { name: 'abc', effectiveDate: '2016-05-01T00:00:00+00:00' }
//    ],
//    abcd: [ 
//      { name: 'abcd', effectiveDate: '2016-02-01T00:00:00+00:00' },
//      { name: 'abcd', effectiveDate: '2016-09-01T00:00:00+00:00' }
//    ]
//  }

const ungroupAndFlatten = compose(ungroup, flatten) // Usage doesn't work.
console.log(ungroupAndFlatten(groupedByName)) 

// Output:
//  var arrs = [
//    {name: 'abc', effectiveDate: "2016-01-01T00:00:00+00:00"},
//    {name: 'abcd', effectiveDate: "2016-02-01T00:00:00+00:00"},
//    {name: 'abcd', effectiveDate: "2016-09-01T00:00:00+00:00"},
//    {name: 'abc', effectiveDate: "2016-04-01T00:00:00+00:00"},
//    {name: 'abc', effectiveDate: "2016-05-01T00:00:00+00:00"},
//  ];
3 Answers
Related