Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform objects pointfree style with Ramda

Tags:

ramda.js

Given the function below, how do I convert it to point-free style? Would be nice to use Ramda's prop and path and skip the data argument, but I just can't figure out the proper syntax.

const mapToOtherFormat = (data) => (
    {
        'Name': data.Name
        'Email': data.User.Email,
        'Foo': data.Foo[0].Bar
    });
like image 519
rickythefox Avatar asked Aug 08 '16 16:08

rickythefox


2 Answers

One option would be to make use of R.applySpec, which creates a new function that builds objects by applying the functions at each key of the supplied "spec" against the given arguments of the resulting function.

const mapToOtherFormat = R.applySpec({
  Name: R.prop('Name'),
  Email: R.path(['User', 'Email']),
  Foo: R.path(['Foo', 0, 'Bar'])
})

const result = mapToOtherFormat({
  Name: 'Bob',
  User: { Email: '[email protected]' },
  Foo: [{ Bar: 'moo' }, { Bar: 'baa' }]
})

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.22.1/ramda.min.js"></script>
like image 135
Scott Christopher Avatar answered Oct 07 '22 21:10

Scott Christopher


Here's my attempt:

const mapToOtherFormat = R.converge(
    (...list) => R.pipe(...list)({}),
    [
      R.pipe(R.view(R.lensProp('Name')), R.set(R.lensProp('Name'))),
      R.pipe(R.view(R.compose(R.lensProp('User'), R.lensProp('Email'))), R.set(R.lensProp('Email'))),
      R.pipe(R.view(R.compose(R.lensProp('Foo'), R.lensIndex(0), R.lensProp('Bar'))), R.set(R.lensProp('Foo')))
    ]
  )

const obj = {Name: 'name', User: {Email: 'email'}, Foo: [{Bar: 2}]}
mapToOtherFormat(obj)

Ramda console

[Edit] We can make it completely point-free:

const mapToOtherFormat = R.converge(
    R.pipe(R.pipe, R.flip(R.call)({})),
    [
      R.pipe(R.view(R.lensProp('Name')), R.set(R.lensProp('Name'))),
      R.pipe(R.view(R.compose(R.lensProp('User'), R.lensProp('Email'))), R.set(R.lensProp('Email'))),
      R.pipe(R.view(R.compose(R.lensProp('Foo'), R.lensIndex(0), R.lensProp('Bar'))), R.set(R.lensProp('Foo')))
    ]
  )

Ramda console

like image 44
homam Avatar answered Oct 07 '22 21:10

homam