underscore.string icon indicating copy to clipboard operation
underscore.string copied to clipboard

Allow conflicting functions via type detection

Open ryanbutterfield opened this issue 14 years ago • 4 comments

Maybe you could suggest (or provide a helper function) that conflicting functions could override the underscore equivalents via wrappers that detect whether the argument passed is a String or other Object.

This would avoid potential bugs when someone uses the wrong function for the wrong type.

This is what I have done in my project and it seems to work well:

_.mixin(_.str.exports());

// functions that conflict with _ and _.prototype
_.mixin(_.reduce(['include', 'contains'], function(memo, f) {
  var str = _.str[f], und = _[f];
  memo[f] = function(obj) {
    return (_.isString(obj) ? str : und).apply(this, arguments);
  };
  return memo;
}, {}));

// functions that just conflict with _.prototype
_.each(['reverse'], function(f) {
  var wstr, str = _.str[f], wund = _.prototype[f]; 
  _.mixin({__tmp: str}); // get access to addToWrapper
  wstr = _.prototype.__tmp;
  _[f] = str;
  _.prototype[f] = function() {
    return (_.isString(this._wrapped) ? wstr : wund).apply(this, arguments);
  };
});

Thanks for a great library!

ryanbutterfield avatar Nov 12 '11 04:11 ryanbutterfield

I think it's the good idea. Could you create the pull request? I think, it can be a part of exports function.

edtsech avatar Nov 16 '11 20:11 edtsech

Any thoughts guys? @epeli, @rwz, @kossnocorp

edtsech avatar May 16 '12 15:05 edtsech

Just a quick comment from the peanut gallery: I've been combining Underscore's contains with Underscore.string's (using type detection) for months now, and it works great! I was actually going to submit a ticket for it when I saw this one; congrats to @ryanbutterfield for beating me to it ;-)

By the way, for what it's worth my implementation of the combined contains is slightly different; if anyone is curious:

var originalContains = _.contains;
var combinedContains = function(initialArg) {
    var contains = typeof initialArg == 'string' ? _.string.contains : originalContains;
    return contains.apply(this, arguments);
};
_.mixin({contains: combinedContains, include: combinedContains});

machineghost avatar Jan 25 '13 01:01 machineghost

It's more than a year later, but this is still a good idea. There should be no need for everyone to roll their own "contains" when Underscore string could very easily merge the base version together. Please consider it!

machineghost avatar Mar 18 '14 23:03 machineghost