2

I have 2 functions that I will add in a lodash flow:

function normalizedFormFields(fields) { // needs only 1 argument
    return _.mapValues( fields, function( value ) {
        return { 'content': value };
    } );
}

function mergedModelAndFormFieldss(model, normalizedFormFields) {
    return _.merge( {}, model, normalizedFormFields )
}

const execution = _.flow( normalizedFormFields, mergedModelAndFormFieldss )

const errorMessageBag = function( fields, model ) {
    return execution( fields, model ) // initiate flow with 2 arguments
}

As you can see the first function normalizedFormFields takes one argument. The second one needs 2: the value returned from the previous function (which is the normal behavior of flow), and another one: model.

But in the errorMessageBag invocation, I launch the flow process with 2 arguments. How to have the second argument, available to the second function in addition to the returned product of first function ? As you see the problem is that the first function in the flow takes and need only one argument. Is this a kind of situation where "curry" should come into play ? Please illustrate.

Robert Brax
  • 6,508
  • 12
  • 40
  • 69

1 Answers1

3

Try this, should work:

function normalizedFormFields(fields) {
    return _.mapValues( fields, function( value ) {
        return { 'content': value };
    });
}

function mergedModelAndFormFieldss(model, normalizedFormFields) {
    return _.merge( {}, model, normalizedFormFields )
}

const errorMessageBag = function( fields, model ) {
    return _.flow(
        normalizedFormFields,
        mergedModelAndFormFieldss.bind(this, model)
    )(fields)
}
Alex M
  • 2,756
  • 7
  • 29
  • 35
  • This does work indeed thanks. Could you please explain briefly the mechanics of bind / this in this context ? – Robert Brax Jul 11 '16 at 11:15
  • 1
    The bind() method creates a new function that, when called, has its `this` keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. – Alex M Jul 11 '16 at 11:20