ericsicons
ericsicons

Reputation: 1495

Javascript Underscore how to share identical callbacks

Is it possible to share identical callbacks? how would I pass the _id as a second parameter to the callback?

e.g.

function getEntry(_id) {

    if (_id === undefined) {
        return false;
    }
    return _(this.scope[this.key]).find(function(entry) {
        return entry._id === _id;
    });
}

function getEntryIndex(_id) {
    if (_id === undefined) {
        return false;
    }
    return _(this.scope[this.key]).findIndex(function(entry) {
        return entry._id === _id;
    });
}

What I would like to do is create one callback -e.g predicate- for both findIndex and find as they are doing the same task, but how to pass _id to predicate?

  function predicate(entry, _id) {
      return entry._id === _id;
  }

  function getEntry(_id) {

      if (_id === undefined) {
          return false;
      }
      return _(this.scope[this.key]).find(predicate);
  }

  function getEntryIndex(_id) {
      if (_id === undefined) {
          return false;
      }
      return _(this.scope[this.key]).findIndex(predicate);
  }

Upvotes: 0

Views: 49

Answers (1)

thefourtheye
thefourtheye

Reputation: 239553

I would recommend restructuring your predicate function, like this

function predicate(_id, entry) {
    return entry._id === _id;
}

And then bind the value of _id when you are passing it to find or findIndex like this

return _(this.scope[this.key]).find(_.partial(predicate, _id)).value();
....
return _(this.scope[this.key]).findIndex(_.partial(predicate, _id)).value();

Note the .value() call at the end. That will give the actual value returned.


In fact, you can refactor your code to use only one getEntry function, like this

function predicate(_id, entry) {
    return entry._id === _id;
}

function getEntry(func, _id) {
    if (_id === undefined) {
        return false;
    }
    return _[func](this.scope[this.key], _.partial(predicate, _id));
}

getEntry('find', 1);
getEntry('findIndex', 1);

Here, we choose the function to be invoked with a parameter, func and then create a new function with _.partial which applies the _id parameter to predicate function.

Upvotes: 1

Related Questions